Comparison between Java local inner class and anonymous inner class

< span style="color:#808080;"> Local inner class and anonymous inner class have the same capabilities and functions, but the name of local inner class is invisible outside the method< pre style="font-family:Menlo;font-size:9pt;">< span style="color:#808080;"> So why do we use local inner classes instead of anonymous inner classes< span style="color:#808080;">  The only reason is that we need a named constructor or an overloaded constructor, and anonymous inner classes can only be used for instance initialization< span style="color:#808080;">  Another reason: more than one object of this inner class is required< pre style="font-family:Menlo;font-size:9pt;">< span style="color:#808080;"> < pre style="font-family:Menlo;font-size:9pt;">< span style="color:#808080;"> Code test: < pre style = "font family: Menlo; font size: 9pt;" >< span style="color:#808080;">

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() {
@Override
public int next() {
System.out.println(name);
return count++;
}
//匿名内部类不能有带名字的构造器,只能有内容初始化;
{
System.out.println("Counter()");
}
};
}

public static void main(String[] args) {
    LocalInnerClass localInnerClass=new LocalInnerClass();
    Counter
            c1=localInnerClass.getCounter("Local inner"),c2=localInnerClass.getCounter2("annomous class");
    for(int i=0;i<7;i++){
        Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(c1.next());
    }
    for(int i=0;i<7;i++){
        Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println(c2.next());
    }
}

}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>