【发布时间】:2014-08-21 19:39:20
【问题描述】:
我是 Java 新手。
我的文件A.java 如下所示:
public class A {
public class B {
int k;
public B(int a) { k=a; }
}
B sth;
public A(B b) { sth = b; }
}
在另一个 java 文件中,我正在尝试创建 A 对象调用
anotherMethod(new A(new A.B(5)));
但由于某种原因我收到错误:No enclosing instance of type A is accessible. Must qualify the allocation with an enclosing instance of type A (e.g. x.new B() where x is an instance of A).
有人可以解释我怎样才能做我想做的事吗?我的意思是,我真的不需要创建A 的实例,然后将其设置为sth,然后将A 的实例提供给该方法,还是有其他方法可以做到这一点?
【问题讨论】:
-
B 不依赖于 A,因此将其设为静态 (
public static class B) 是有意义的 - 然后您的代码就可以工作了。另见:stackoverflow.com/questions/9560600/… -
好吧,我不知道为什么我没有想到使用
static,但实际上它是解决方案。谢谢
标签: java class inner-classes