内部类

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类。

转载于:https://my.oschina.net/u/3230371/blog/3001960

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值