Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
要查看正在使用的内部类,首先要考虑一个数组。在下面的示例中,你将创建一个数组,用整数值填充它,然后仅按升序输出数组的偶数索引值。
接下来的 DataStructure.java 示例包括:
DataStructure 外部类,包括用于创建 DataStructure 实例的构造函数,其中包含一个填充了连续整数值(0,1,2,3 等)的数组以及打印具有偶数索引值的数组元素的方法。EvenIterator 内部类,它实现 DataStructureIterator 接口,继承 Iterator< Integer> 接口。迭代器用于逐步遍历数据结构,并且通常具有测试最后一个元素,检索当前元素以及移动到下一个元素的方法。DataStructure 对象(ds)的 main 方法,然后调用 printEven 方法打印数组 arrayOfInts 中具有偶数索引的元素。
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
请注意,EvenIterator 类直接引用 DataStructure 对象的 arrayOfInts 实例变量。
你可以使用内部类来实现帮助程序类,例如本示例中显示的帮助程序类。要处理用户界面事件,你必须知道如何使用内部类,因为事件处理机制会广泛使用它们。
还有两种类型的内部类。你可以在方法体内声明内部类。这些类称为 local classes (局部类)。你还可以在方法体内声明内部类,而无需命名该类。这些类称为 anonymous classes (匿名类)。
对于内部类,可以使用与外部类的其他成员相同的修饰符。例如,你可以使用访问修饰符 private,public 和 protected 来限制对内部类的访问,就像你使用它们来限制访问其他类成员一样。