在java中在外部类之外创建内部类的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24506971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating instance of inner class outside the outer class in java
提问by burtek
I'm new to Java.
我是 Java 新手。
My file A.java
looks like this:
我的文件A.java
看起来像这样:
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
在另一个 java 文件中,我试图创建 A 对象调用
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).
但由于某种原因我得到错误: 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?
有人可以解释我如何做我想做的事吗?我的意思是,我真的需要创建实例A
,然后设置它sth
,然后将实例提供A
给方法,还是有另一种方法可以做到这一点?
采纳答案by monkHyman
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.
如果您想要的只是为了可读性而不是实例关联而嵌套类的一种方式,那么您需要一个静态内部类。
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);
回答by rachana
Outside the outer class, you can create instance of inner class like this
在外部类之外,您可以像这样创建内部类的实例
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
In your case
在你的情况下
A a = new A();
A.B b = a.new B(5);
For more detail read Java Nested Classes Official Tutorial
更多细节请阅读Java 嵌套类官方教程
回答by shmosel
Interesting puzzle there. Unless you make B
a static class, the only way you can instantiate A
is by passing null
to the constructor. Otherwise you would have to get an instance of B
, which can only be instantiated from an instance of A
, which requires an instance of B
for construction...
那里有有趣的谜题。除非您创建B
静态类,否则您可以实例化的唯一方法A
是传递null
给构造函数。否则,您将不得不获得 的实例B
,该实例只能从 的实例中实例化A
,而这需要一个 的实例B
用于构造...
The null
solution would look like this:
该null
解决方案是这样的:
anotherMethod(new A(new A(null).new B(5)));