【问题标题】:Instantiate an Inner class from within a static method of its enclosing Class [duplicate]从其封闭类的静态方法中实例化一个内部类[重复]
【发布时间】:2012-09-10 12:30:47
【问题描述】:

我们知道静态上下文不能引用任何类型的任何实例,但是 main 方法会发生什么,下面的代码示例如何编译没有问题:

public class MyOuter
{
    public static void main(String[] args) 
    {
        MyOuter mo = new MyOuter(); // gotta get an instance!
        MyOuter.MyInner inner = mo.new MyInner();
        inner.seeOuter();

        //Or

        MyOuter.MyInner inner = new MyOuter().new MyInner();
    } 

    class MyInner
    {
        public void seeOuter(){}
    }
 }

是否禁止在其封闭类的静态上下文中实例化内部类?

【问题讨论】:

    标签: java inner-classes scjp


    【解决方案1】:

    是否禁止在其封闭类的静态上下文中实例化内部类?

    不-禁止实例化内部类没有封闭类的实例。在您的情况下,您 确实 有一个封闭类的实例:

    new MyOuter().new MyInner();
    

    没关系。

    您通常可以在不从实例方法中指定封闭类的情况下逃脱的唯一原因是它等效于

    // Within an instance method
    this.new MyInner();
    

    请参阅section 15.9.2 of the JLS 了解更多详情。您的构造函数调用是“合格的类实例创建表达式”。

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 2012-09-23
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多