1.局部内部类
注:方法中的内部类
局部类不能用public或private访问说明符进行声明。它的作用域被限定在声明这个局部类的块中。局部类对外部世界可以完全地隐藏起来。
2.由外部方法访问final变量
它们不仅能够访问包含它们的外部类,还可以访问局部变量。不过,那些局部变量必须被声明为final。
//错误示范
int counter = 0;
Date[] dates = new Date[100];
for(int i = 0; i<dates.length;i++)
dates[i] = new Date()
{
public int compareTo(Date other)
{
counter++;//ERROR
return super.compareTo(other);
}
};
Arrays.sort(dates);
System.out.println(counter+" comparisons");
应该为
final int[] counter = new int[1];
Date[] dates = new Date[100];
for(int i = 0; i<dates.length;i++)
dates[i] = new Date()
{
public int compareTo(Date other)
{
counter[0]++;
return super.compareTo(other);
}
};
Arrays.sort(dates);
System.out.println(counter+" comparisons");
注意:有些程序员对于编译器在背后生成堆对象感动惧怕,而采用final限制代替。
3.匿名内部类
//父类
new SuperType(construction parameters){
inner class methods and data
}
//接口
new InterfaceType(){
}
//匿名子类
invite(new ArrayList<String>(){{add("Harry");add("Tony");}})
//注意这里的双括号。外层括号建立了ArrayList的一个匿名子类。内层括号则是一个对象构造块。
4.静态内部类(非方法内)
class ArrayAlg{
...
public static class Pair{
...
}
public static Pair minmax(double[] d){
...
return new Pair(min,max);
}
...
}
注意:只有内部类可以声明为static。在此,必须使用静态内部类,这是由于内部类对象是在静态方法中构造的。 在内部类不需要访问外围类对象的时候,应该使用静态内部类。
注意:声明在接口中的内部类自动称为static和public类。