[英]I have an object of an outer class. How do I get the object of the inner class from it?
public class Class1 {
public Class2 getClass2() {
//How can I implement this method?
}
public class Class2 {
//...
}
}
I just can't get it done, even though it should only be one line of code... 即使只是一行代码,我也无法完成它...
You should not do this. 您不应该这样做。 The inner class should be used in the outer class and not elsewhere.
内部类应在外部类中使用,而不能在其他地方使用。 If you need an instance of the inner class then it should be not an inner class.
如果需要内部类的实例,则它不应是内部类。
Just create a getter method in the outer class like this. 像这样在外部类中创建一个getter方法。
public class Class1 {
public Class2 getClass2() {
//How can I implement this method?
}
public Class2 getClass2() {
return new Class2();
}
public class Class2 {
//...
}
}
I think you are getting the concept of inner classes wrong. 我认为您弄错了内部类的概念。 In your example, you have a public inner class.
在您的示例中,您有一个公共内部类。 That doesn't mean that your
Class1
has exactly one object of Class2
. 这并不意味着您的
Class1
恰好具有Class2
一个对象。 You can still create as many objects of Class2
as you like. 您仍然可以根据需要创建任意数量的
Class2
对象。 If you want to do this outside of Class1
use new Class1.Class2()
. 如果要在
Class1
之外执行此操作,请使用new Class1.Class2()
。 While this is possible, it would be bad design as galovics correctly mentioned in his answer. 尽管这是可能的,但正如galovics在他的回答中正确提到的那样,这将是一个糟糕的设计。
If what you are trying to achieve is having one object reference to a Class2
object inside Class1
, use a field of type Class2
in Class1
and a matching getter method: 如果你正在努力实现的是具有一个对象引用
Class2
内对象Class1
,使用类型的字段Class2
中Class1
和匹配的getter方法:
public class Class1 {
private Class2 class2instance = new Class2();
public Class2 getClass2() {
return class2instance;
}
private class Class2 {
//...
}
}
public class Class1 {
private Class2 class2 = new Class2();
public Class2 getClass2() {
return class2;
}
public class Class2 {
//...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.