从内部类对象获取外部类对象
2022-08-31 05:22:15
我有以下代码。我想获得外部类对象,我使用它创建了内部类对象。我该怎么做?inner
public class OuterClass {
public class InnerClass {
private String name = "Peakit";
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
InnerClass inner = outer.new InnerClass();
// How to get the same outer object which created the inner object back?
OuterClass anotherOuter = ?? ;
if(anotherOuter == outer) {
System.out.println("Was able to reach out to the outer object via inner !!");
} else {
System.out.println("No luck :-( ");
}
}
}
编辑:好吧,你们中的一些人建议通过添加一个方法来修改内部类:
public OuterClass outer() {
return OuterClass.this;
}
但是,如果我无法控制修改内部类,那么(只是为了确认)我们是否有其他方法从内部类对象获取相应的外部类对象?