可以在代码块里创建内部类,典型的方法是在一个方法体的里面创建,局部内部类不能有访问说明符,因为它不是外围类的一部分,但是可以访问当前代码块的常量,以及此外围类的所有成员,下面分别对局部内部类和匿名内部类进行了比较

//: innerclasses/LocalInnerClass.java
// Holds a sequence of Objects.
package object;
import static net.util.Print.*; interface Counter {
int next();
} public class LocalInnerClass {
private int count = 0;
Counter getCounter(final String name) {
// A local inner class:
class LocalCounter implements Counter { //局部内部类
public LocalCounter() {
// Local inner class can have a constructor
print("LocalCounter()");
}
public int next() {
printnb(name); // Access local final
return count++;
}
}
return new LocalCounter();
}
// The same thing with an anonymous inner class:
Counter getCounter2(final String name) {
return new Counter() { //匿名内部类
// Anonymous inner class cannot have a named
// constructor, only an instance initializer:
{
print("Counter()");
}
public int next() {
printnb(name); // Access local final
return count++;
}
};
}
public static void main(String[] args) {
LocalInnerClass lic = new LocalInnerClass();
Counter
c1 = lic.getCounter("Local inner "),
c2 = lic.getCounter2("Anonymous inner ");
for(int i = 0; i < 5; i++)
print(c1.next());
for(int i = 0; i < 5; i++)
print(c2.next());
}
} /* Output:
LocalCounter()
Counter()
Local inner 0
Local inner 1
Local inner 2
Local inner 3
Local inner 4
Anonymous inner 5
Anonymous inner 6
Anonymous inner 7
Anonymous inner 8
Anonymous inner 9
*///:~

局部内部类和匿名内部类都实现了这个功能, 它么具有相同的行为和能力,既然局部内部类的名字在方法外是不可见的,那为什么还要使用基本内部类呢,唯一的理由是我们需要一个已命名的构造器,或需要重构构造器,而匿名构造器只能用于实例初始化

另外一个理由是,我们需要不止一个该内部类的对象

05-13 02:37