内部类示例
要查看正在使用的内部类,请首先考虑一个数组。在下面的示例中,创建一个数组,将其填充为整数值,然后仅以升序输出该数组偶数索引的值。
以下DataStructure.java示例包括:
-
DataStructure
外部类,包括一个用于创建DataStructure
的实例的构造函数,该实例包含一个用连续整数值(0、1、2、3 等填充)的数组,以及一种打印具有偶数索引的数组元素的方法值。 -
EvenIterator
内部类,实现DataStructureIterator
interface,该interface扩展了Iterator<
Integer>
interface。迭代器用于单步执行数据结构,通常具有测试最后一个元素,检索当前元素并移至下一个元素的方法。 -
实例化
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
实例变量。
您可以使用内部类来实现帮助程序类,如本示例中所示。要处理用户interface事件,您必须知道如何使用内部类,因为事件处理机制会大量使用它们。
本地和匿名类
内部类有两种其他类型。您可以在方法体内声明一个内部类。这些类称为local classes。您也可以在方法体内声明内部类,而无需命名该类。这些类称为anonymous classes。
Modifiers
您可以对内部类使用与外部类其他成员相同的修饰符。例如,您可以使用访问说明private
,public
和protected
来限制对内部类的访问,就像您使用它们来限制对其他类成员的访问一样。