在java中创建外部类外部的内部类的实例
我是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 AB(5)));
但由于某种原因,我得到错误: No enclosing instance of type A is accessible. Must qualify the allocation with an enclosing instance of type A (egxnew B() where x is an instance of A).
No enclosing instance of type A is accessible. Must qualify the allocation with an enclosing instance of type A (egxnew B() where x is an instance of A).
有人可以解释我怎么能做我想做的事情? 我的意思是,我是否真的需要创建A
实例,然后设置它,然后将A
的实例A
给方法,还是有其他方法可以做到这一点?
在您的示例中,您有一个内部类,它始终绑定到外部类的实例。
如果,你想要的只是一种嵌套类的可读性而不是实例关联的方式,那么你需要一个静态的内部类。
public class A { public static class B { int k; public B(int a) { k=a; } } B sth; public A(B b) { sth = b; } } new AB(4);
在外部类之外,您可以像这样创建内部类的实例
Outer outer = new Outer(); Outer.Inner inner = outer.new Inner();
在你的情况下
A a = new A(); AB b = a.new B(5);
有关更多详细信息,请阅读Java嵌套类官方教程
那里有趣的谜题。 除非你使B
成为静态类,否则实例化A
的唯一方法是将null
传递给构造函数。 否则你必须得到一个B
的实例,它只能从A
的实例中实例化,这需要一个B
的实例来构造……
null
解决方案如下所示:
anotherMethod(new A(new A(null).new B(5)));