内部类

来源:互联网 发布:孙侨潞淘宝店叫什么 编辑:程序博客网 时间:2024/05/17 00:50

为了更好的说明一个内部类是如何使用的,让我们来用一下数组描述。在下面例子中,我们会创建一个整数数组。然后把数组里面的偶数以升序的方式输出出来。

让我们来具体看看 DataStructure.java 包含了什么内容吧:

  • DataStructure外部类,包含了一个构造方法,方法会实例化一个DataStructure对象,并且在方法内部创建了一个连续整数的数组。还有一个方法用来输出有偶数下标的数组元素。
  • 有一个EvenIterator内部类,它实现了DataStructureIterator接口, DataStructureIterator是从Iterator接口继承来的。迭代器(Iterator)就是用来遍历数据,它有自己的方法来判断是不是最后一个元素、获取当前元素以及移到到下个元素。
  • 有一个main方法,里面创建了一个DataStructure对象,会调用printEven方法来输出数组有偶数下标的数组元素

public class DataStructure {        // Create an array    private final static int SIZE = 15;    private int[] arrayOfInts = new int[SIZE];        public DataStructure() {        // fill the array with ascending integer values        for (int i = 0; i < SIZE; i++) {            arrayOfInts[i] = i;        }    }        public void printEven() {                // Print out values of even indices of the array        DataStructureIterator iterator = this.new EvenIterator();        while (iterator.hasNext()) {            System.out.print(iterator.next() + " ");        }        System.out.println();    }        interface DataStructureIterator extends java.util.Iterator<Integer> { }     // Inner class implements the DataStructureIterator interface,    // which extends the Iterator<Integer> interface        private class EvenIterator implements DataStructureIterator {                // Start stepping through the array from the beginning        private int nextIndex = 0;                public boolean hasNext() {                        // Check if the current element is the last in the array            return (nextIndex <= SIZE - 1);        }                        public Integer next() {                        // Record a value of an even index of the array            Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);                        // Get the next even element            nextIndex += 2;            return retValue;        }    }        public static void main(String s[]) {                // Fill the array with integer values and print out only        // values of even indices        DataStructure ds = new DataStructure();        ds.printEven();    }}

输出结果就是:

0 2 4 6 8 10 12 14 

就像这个例子一样,你可以使用内部类实现一些辅助功能。如果要处理用户接口事件,你就更需要知道如何使用内部类了, 因为事件处理机制里面恰恰扩展使用了内部类。


局部和匿名类

还有另外两种类型的内部类:你可以在一个方法里面定义一个内部类,也就是局部类 (关于局部类,自行查找吧,翻译者不干了); 你也可以在方法里面定义一个内部类,但是不指定类的名字,也就是匿名类(关于匿名类,自行查找吧,翻译者也不干了)。

修饰符

对于内部类,你可以和之前一样用同样的修饰符, 反正外部类的成员能用什么修饰符,它都能用。就像Private, Protected, Public都能用。



0 0
原创粉丝点击