您的位置:首页 > 其它

No enclosing instance of type B is accessible. Must qualify the allocation with an enclosing ins (20

2012-08-07 12:54 585 查看
编译时出现:No enclosing instance of type B is accessible. Must qualify the allocation with an enclosing instance of type B(e.g. x.new B() where x is an instance of B).

B指代内部类。

根据提示,没有可访问的内部类B的实例,必须分配一个合适的内部类B的实例(如x.new B(),x必须是B的实例)

原来内部类B是动态的,也就是以class开头。

在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。

所以解决办法是将class改为static class.

下文摘录网上描述的一段话:

如果一个成员变量被声明为static,它就能够在它的类的任何对象创建之前被访问,而不必引用任何对象。

你可以将方法和变量都声明为static。static成员最常见的例子是main()。因为在程序开始执行时必须调用main(),所以它被声明为static。

下面是例子:

public class A {
public static void main(String[] args) {
new B().print();
}

static class B {	//必须用static
public void print() {
System.out.println("Hello, world!");
}
}
}


或者:

public class A {
public static void main(String[] args) {
A a = new A();	//必须先建立一个对象
a.new B().print();
}

class B {
public void print() {
System.out.println("Hello, world!");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐