在实例上调用new,比如pc.new InnerClass() - 发生了什么?

时间:2015-02-14 12:18:18

标签: java syntax

我对在实例上调用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");
        }
    }

}

1 个答案:

答案 0 :(得分:3)

免责声明:您使用的术语“父类”和“子类”在您的示例中不正确,因此下面的示例将使用正确的术语“外部类”和“内部类” (感谢@eis提示)。


  

JAVA文档中描述了什么?

请参阅@eis'评论我的答案以获取链接。

  

这是一个应该使用的推荐解决方案,还是有更好的方法?

这取决于你需要它。 如果SubClass不需要ParentClass实例的任何信息,那么它可以(并且应该)被设为静态或提取为不再是内部类。在这种情况下,您只需在其上调用new,而无需ParentClass的实例。

  

为什么不是一个简单的“新”工作?

因为SubClass可能引用周围实例的信息,这需要您指定该实例。它不是一个子类,它扩展ParentClass,而是它的类型成为外部类的成员

考虑这一点(并在行动here中看到它):

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应该返回什么,因为它已连接到其周围类型的实例(而不是只是类型本身)。