Must qualify the allocation with an enclosing instance of type AAA (e.g. x.new A() where x

来源:互联网 发布:手机淘宝店的店招尺寸 编辑:程序博客网 时间:2024/05/21 14:19

今天在写一个程序的时候在一个类中写了内部类。在main()中进行了实现,
但是在编译的时候进行了报错。自己也不知道错在哪里就出现了这样的英文。
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
No enclosing instance of type AAA is accessible. Must qualify the allocation with an enclosing instance of type AAA (e.g. x.new A() where x is an instance of AAA).

at a.AAA.main(AAA.java:24)
如图:

后来发现是这样的原因:
在实例化一个类的时候只能对在类中的进行实例化,
例如代码:

package a;

public class AAA {

int a;
public AAA(int m){
this.a = m;
System.out.println(“可以输出a的值是:\t” + a);
}

class BBB{
int b;
public BBB(int n){
this.b = n;
System.out.println(“可以输出b的值是: \t” + b);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
AAA aa = new AAA(100);
BBB bb = new BBB(50);//这里出现的错误,因为BBB内部类在AAA类中,因此实例化应该在AAA构造方法或者AAA内部进行实例化。
//或者吧class改成static class BBB{………………..}.
//具体这里为什么要改成static class。是因为这样的话就成了静态内部类。
}

}

再找资料的同事还发现一种情况。

根据提示,没有可访问的内部类E的实例,必须分配一个合适的内部类E的实例(如x.new A(),x必须是E的实例。)看着这句提示,我就纳闷了,我已经用new实例化了这个类,为什么还不行呢。
于是百度谷歌了一下相关资料。原来我写的内部类是动态的,也就是开头以public class开头。而主程序是public static class main。在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。所以在不做其他变动的情况下,最简单的解决办法是将public class改为public static class。
希望对各位有所帮助。

0 0