根据 JLS:
15.9.5 Anonymous Class Declarations An anonymous class declaration is automatically derived from a class instance creation expression by the compiler.
An anonymous class is never abstract (§8.1.1.1). An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.2). An anonymous class is always implicitly final (§8.1.1.2).
这似乎是一个特定的设计决定,所以它可能有一些历史。
如果我选择这样的类(class):
SomeType foo = new SomeType() {
@Override
void foo() {
super.foo();
System.out.println("Hello, world!");
}
};
如果我愿意,为什么不允许我再次子类化它?
SomeType foo = new SomeType() {
@Override
void foo() {
super.foo();
System.out.println("Hello, world!");
}
} {
@Override
void foo() {
System.out.println("Hahaha, no super foo for you!");
}
};
我并不是说我一定要这样做,或者甚至可以想出我会这样做的原因。但我很好奇为什么会这样。
最佳答案
嗯,能够子类化一个匿名类是非常无用的。您可以引用匿名类的唯一位置是在定义它的语句中(如您假设的伪代码示例所示)。这意味着程序将保证永远不会创建匿名父类(super class)的任何实例——并且智能编译器应该能够将两个定义折叠到一个类中。
更实际的是,当一个类是 final 时,编译器和 VM 可以自由地在调用站点内联它的方法。因此,在自然不可能扩展给定类的任何情况下,使此类本质上成为最终类是有意义的。
关于java - 为什么所有匿名类都是隐式最终的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8584034/