在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)));