我有以下代码。我想掌握用来创建内部类对象的外部类对象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;
}
但是,如果我没有控制权来修改内部类,那(只是确认一下)我们还有其他方法可以从内部类对象中获取相应的外部类对象吗?