我对在实例上调用new的可能性感到困惑,比如
InnerClass sc = pc.new InnerClass();
我知道如何使用它,但我的问题是如何充分理解这一点。类似:
JAVA文档中对它的描述在哪里?
这是应该使用的推荐解决方案,还是有更好的方法?
为什么一个简单的"新"不起作用?
我在一个代码示例中看到了它,并且我已经了解到我无法在静态上下文中使用普通的"new"。
这是作为可运行示例的完整上下文:
class ParentClass{
ParentClass(){
}
public static void main(String[] args){
ParentClass pc = new ParentClass();
InnerClass sc = pc.new InnerClass();
}
class InnerClass {
InnerClass() {
System.out.println("I'm OK");
}
}
}
免责声明:您在示例中使用的术语"父类"one_answers"子类"不正确,因此我在下面的示例中将使用正确的术语"外部类别"one_answers"内部类别"(感谢@eis的提示)。
JAVA文档中对它的描述在哪里?
请参阅@eis对我的回答的评论以获取链接。
这是应该使用的推荐解决方案,还是有更好的方法?
这取决于你需要它做什么。如果SubClass
不需要ParentClass
的实例的任何信息,则可以(也应该)将其设置为静态或提取为不再是内部类。在这种情况下,您可以直接在上面调用new
,而不需要ParentClass
的实例。
为什么一个简单的"新"不起作用?
因为SubClass
可能引用了周围实例的信息,这需要您指定该实例。从扩展ParentClass
的意义上说,它不是一个子类,但它的类型变成了外部类的成员。
考虑一下(并在这里看到它的作用):
public class OuterClass {
private int field;
public OuterClass(int field) {
this.field = field;
}
class InnerClass {
public int getOuterClassField() {
// we can access the field from the surrounding type's instance!
return OuterClass.this.field;
}
}
public static void main(String[] args) throws Exception {
OuterClass parent = new OuterClass(42);
// prints '42'
System.out.println(parent.new InnerClass().getOuterClassField());
// cannot work as it makes no sense
// System.out.println(new InnerClass().getOuterClassField());
}
}
如果您能够简单地执行new InnerClass()
,则无法知道getOuterClassField
应该返回什么,因为它连接到其周围类型的实例(而不仅仅是类型本身)。