interface Counter{
int next();
}
public class LocalInnerClass{
private int count=0;
Counter getCounter(final String name){
class LocalCounter implements Counter{
public LocalCounter(){
System.out.println("LocalCounter");
}
public int next(){
System.out.println(name); return count++;
}
}
return new LocalCounter();
}
Counter getCounter2(final String name){
return new Counter(){
{
System.out.println("Counter");
}
public int next(){
System.out.println(name);
return count++;
}
};
}
public static void main (String [] args){
LocalInnerClass c=new LocalInnerClass();
Counter
a1=c.getCounter("Local inner"),a2=c.getCounter2("Anonymous inner");
for(int i=0;i<5;i++)
System.out.println(a1.next());
for(int j=0;j<5;j++)
System.out.println(a2.next());
}
}
从上述例子中可以看出局部内部类与匿名内部类均可实现所需功能,但是其区别在于局部内部类有一个已命名的构造器,且可以产生内部类的对象,而匿名内部类只能实例初始化,这是他们的区别,由此也可了解其使用范围的不同。