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");
}
}
编译器为什么将匿名类创建为静态?如果它是非静态会发生什么?
答案 0 :(得分:7)
如图所示的代码在静态上下文中创建一个匿名类。内部类(或非静态嵌套类)需要引用封闭对象(*)。在这种情况下,没有封闭对象,因为它是在静态方法中创建的,因此使用静态嵌套类是唯一有效的选项。
通过将您的示例转换为
,可以很容易地证明这一点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");
}
}
}
编译它会产生错误
非静态变量,不能从静态上下文引用
如果将其更改为:
,它将编译得很好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
作为该参数的值传递。静态嵌套类不是这种情况。