我是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文件中,我正在尝试创建一个调用的对象
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
的实例提供给方法,还是有其他方法可以执行此操作? / p>
答案 0 :(得分:23)
在外部类之外,您可以像这样创建内部类的实例
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
在你的情况下
A a = new A();
A.B b = a.new B(5);
有关详细信息,请参阅Java Nested Classes Official Tutorial
答案 1 :(得分:10)
在您的示例中,您有一个内部类,它始终与外部类的实例绑定。
如果你想要的只是一种嵌套类以便于阅读而不是实例关联的方法,那么你需要一个静态的内部类。
public class A {
public static class B {
int k;
public B(int a) { k=a; }
}
B sth;
public A(B b) { sth = b; }
}
new A.B(4);
答案 2 :(得分:1)
那里有趣的谜题。除非你使B
成为静态类,否则实例化A
的唯一方法是将null
传递给构造函数。否则,您必须获取B
的实例,该实例只能从A
的实例实例化,这需要B
的实例进行构建...
null
解决方案如下所示:
anotherMethod(new A(new A(null).new B(5)));