abstract class Person {
abstract void eat();
}
class TestAnonymousInner {
public static void main(String args[]){
Person p=new Person() {
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
编译器生成的内部类
static class TestAnonymousInner$1 extends Person
{
TestAnonymousInner$1(){}
void eat()
{
System.out.println("nice fruits");
}
}
编译器出于什么原因将匿名类创建为静态类?如果它是非静态的会发生什么?
最佳答案
所示代码在静态上下文中创建了一个匿名类。内部类(或非静态嵌套类)需要引用封闭对象 (*)。在这种情况下,没有封闭对象,因为它是在静态方法中创建的,因此使用静态嵌套类是唯一有效的选择。
这可以很容易地通过将您的示例转换为
来证明public class TestInner {
public static void main(String args[]){
Person p = new Testperson();
p.eat();
}
public class Testperson extends Person {
void eat() {
System.out.println("nice fruits");
}
}
}
编译会报错
non-static variable this cannot be referenced from a static context
如果你把它改成:
public class TestInner {
public static void main(String args[]){
Person p = new Testperson();
p.eat();
}
public static class Testperson extends Person {
void eat() {
System.out.println("nice fruits");
}
}
}
*:编译器将修改内部类的构造函数以接受封闭对象作为参数,并且构造函数调用将被重写以传递 this
作为该参数的值。静态嵌套类不是这种情况。
关于java - 为什么 Java 在内部将匿名类创建为静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50273342/