一、嵌套类(Nested Class)分为:内部类(Inner Class)、静态嵌套类(Static Nested Class)
二、写法:
class OutClass{
static class StaticNestedClass{
...
}
class InnerClass{
...
}
}
三、为什么要用嵌套类:
1、当仅希望在某个类中使用一个类时,用嵌套类的写法,就起到封装的作用。
2、提高代码可读性,与可维护性。
四、用例:
public class DataStructure {
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
InnerEvenIterator iterator = new InnerEvenIterator();//外部类中直接调用内部类
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
private class InnerEvenIterator {//非静态内部类
private int next = 1;
public boolean hasNext() {
return (next <= SIZE - 1);
}
public int getNext() {
int retValue = arrayOfInts[next];//直接访问外部类变量
next += 2;
return retValue;
}
}
private void outPrivateFunction(){}
private static void staticOutPrivateFunction(){}
private static int i;
static class NestedClass//静态嵌套类
{
NestedClass(){}
int i = 8;
void access()
{
System.out.println(i);//自身变量的访问
System.out.println(DataStructure.i);//外部类变量的访问
DataStructure.staticOutPrivateFunction();//调用外部类静态方法
new DataStructure().outPrivateFunction();
}
}
interface Work //接口也可作为嵌套类,实现匿名嵌套类,参数嵌套类类似
{
public int Money();
}
public static void main(String s[]) {
DataStructure.InnerEvenIterator ie = new DataStructure().new InnerEvenIterator(); //创建非静态内部类实例
DataStructure.NestedClass dn = new DataStructure.NestedClass(); //创建静态嵌套类实例
DataStructure ds = new DataStructure();
ds.printEven();
dn.access();
new Work()
{
public int Money(){ return 2000;};
}.Money();
}
}