您的位置:首页 > 编程语言 > Java开发

javaSE_8系列博客——Java语言的特性(三)--类和对象(16)--嵌套类(内部类的示例)

2017-05-13 22:14 921 查看
要看到正在使用的内部类,首先考虑一个数组。在下面的示例中,您将创建一个数组,用整数值填充数组,然后按升序排列数组的均匀索引值。

下面的DataStructure.java示例包括:

DataStructure外部类,其中包含一个构造函数,用于创建包含连续整数值(0,1,2,3等)的数组的DataStructure实例,以及打印具有均匀索引的数组元素值的方法。

EvenIterator内部类实现了DataStructureIterator接口,它扩展了Iterator

接口。迭代器用于遍历数据结构,通常有方法来测试最后一个元素,检索当前元素,并移动到下一个元素。

实例化DataStructure对象(ds)的主要方法,然后调用printEven方法打印具有均匀索引值的数组arrayOfInts的元素。

public class DataStructure{

private static final int SIZE = 15;

private int[] arrayInts = new int[SIZE];

private DataStructure(){

for(int i = 0; i < SIZE ; i++){
arrayInts[i] = i;
}
}

public void printEvent(){

//new an object from inner class
DataStructureIterator iterator = this.new EventIterator();
//if the array do hasNext then print the valus of current index to the windowns
while(iterator.hasNext()){
System.out.println("valueOf next index is " + iterator.next() + " ");
}
System.out.println();
}

//define a interface which extends java.util.iterator<Integer>
interface DataStructureIterator extends java.util.Iterator<Integer>{}

//define a private inner class and let it impletments the interface
private class EventIterator implements DataStructureIterator{

private int nextIndex = 0;

public boolean hasNext(){

return (nextIndex <= SIZE -1);
}

public Integer next(){

Integer retValue = Integer.valueOf(arrayInts[nextIndex]);

nextIndex +=2;

return retValue;
}

}

public static void main(String[] args){

//new  a object and assign it to the reference
DataStructure ds = new DataStructure();
//call the printEvent mothod
ds.printEvent();
}

}


输出为:

valueOf next index is 0
valueOf next index is 2
valueOf next index is 4
valueOf next index is 6
valueOf next index is 8
valueOf next index is 10
valueOf next index is 12
valueOf next index is 14


请注意:

EvenIterator类直接引用DataStructure对象的arrayOfInts实例变量。 您可以使用内部类来实现助手类,如本例所示。要处理用户界面事件,您必须知道如何使用内部类,因为事件处理机制广泛使用它们。

本地类(局部类)和匿名类

还有两种类型的内部类。您可以在方法体内声明一个内部类(局部类)。这些类被称为本地类。您也可以在方法正文中声明一个内部类,而不必命名该类。这些类被称为匿名类。

修饰符

您可以对外部类的其他成员使用内部类使用相同的修饰符。例如,您可以使用private,public和protected的访问说明符来限制对内部类的访问,就像使用它们来限制对其他类成员的访问一样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java se java
相关文章推荐