在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 A.B(5)));
,但由于某种原因,我收到错误:无法访问类型 A 的封闭实例。必须用 A 类型的封闭实例来限定分配(例如 xnew B(),其中 x 是 A 的实例)。
有人可以解释一下我该如何做我想做的事情吗?我的意思是,我真的需要创建 A
的实例,然后设置它的 sth
,然后将 A
的实例提供给该方法,或者还有另一种方法可以做到这一点吗?
I'm new to Java.
My file A.java
looks like this:
public class A {
public class B {
int k;
public B(int a) { k=a; }
}
B sth;
public A(B b) { sth = b; }
}
In another java file I'm trying to create the A object calling
anotherMethod(new A(new A.B(5)));
but for some reason I get error: 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).
Can someone explain how can I do what I want to do? I mean, do I really nead to create instance of A
, then set it's sth
and then give the instance of A
to the method, or is there another way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在外部类之外,您可以像这样创建内部类的实例
在您的情况下
有关更多详细信息,请阅读 Java嵌套类官方教程
Outside the outer class, you can create instance of inner class like this
In your case
For more detail read Java Nested Classes Official Tutorial
在您的示例中,您有一个始终与外部类的实例绑定的内部类。
如果您想要的只是一种嵌套类以提高可读性而不是实例关联的方式,那么您需要一个静态内部类。
In your example you have an inner class that is always tied to an instance of the outer class.
If, what you want, is just a way of nesting classes for readability rather than instance association, then you want a static inner class.
那里有有趣的谜题。除非将
B
设为静态类,否则实例化A
的唯一方法是将null
传递给构造函数。否则,您将必须获取B
的实例,它只能从A
的实例实例化,而 A 的实例需要B
的实例构造...null
解决方案如下所示:Interesting puzzle there. Unless you make
B
a static class, the only way you can instantiateA
is by passingnull
to the constructor. Otherwise you would have to get an instance ofB
, which can only be instantiated from an instance ofA
, which requires an instance ofB
for construction...The
null
solution would look like this: