错误:
No enclosing instance of type Test1 is accessible. Must qualify the allocation with an enclosing instance of type Test1 (e.g. x.new A() where x is an instance of Test1).
代码:public class Test1 {
int x = 0;
public static void main(String args[]){
new A();
}
class A{
public A(){
System.out.println(x);
}
}
}
为什么会有错误呢?
我们都知道,在执行main()函数时Test1类还没有生成,而A是内部类,在生成内部类的时候必须首先生成外部类。
所以问题的解决方式有两种:
1.将class A改为static class A,并把int x = 0;改为static int x = 0;
这是根据编辑器提示错误改的,静态方法不能调用非静态方法或类、属性
2.将生成A的代码更改如下
new Test1().new Test1a();全部代码:
public class Test1 {
int x = 0;
public static void main(String args[]){
//new Test1a();
new Test1().new Test1a();
}
class Test1a{
public Test1a(){
System.out.println(x);
}
}
}
如此即可。
本文解析了Java中尝试直接实例化非静态内部类时出现的错误,并提供了两种解决方案:一是通过使内部类和成员变量变为静态,二是先实例化外部类再创建内部类实例。
1万+

被折叠的 条评论
为什么被折叠?



