java – 在范围内没有封闭类型的实例

我调查java内部类.

我写了一个例子:

public class Outer {
    public Outer(int a){}

    public class Inner {
        public Inner(String str, Boolean b){}
    }

    public static class Nested extends Inner{
        public static void m(){
            System.out.println("hello");
        }
        public Nested(String str, Boolean b , Number nm)   { super("2",true);   }
    }

    public class InnerTest extends Nested{
        public InnerTest(){  super("str",true,12);  }
    }
}

我使用以下字符串从main调用它:

 new Outer(1).new Inner("",true);

我看到编译错误:

  java: no enclosing instance of type testInheritancefromInner.Outer is in scope

你能解释一下这种情况吗?

UPDATE

最佳答案
内心是一个内在阶级.它只能在包含Inner类定义的类的封闭实例时创建.

但是,您已经创建了一个静态嵌套类Nested,它从此类扩展而来.当您尝试调用超级构造函数时

public Nested(String str, Boolean b , Number nm)   { super("2",true);   }

它会失败,因为Inner的超级构造函数依赖于Outer的一个实例,它在Nested类的静态上下文中不存在. Jon Skeet provides a solution.

解决方案的解释见于JLS here.

Superclass constructor invocations may be subdivided:

  • Unqualified superclass constructor invocations begin with the keyword
    super (possibly prefaced with explicit type arguments).

  • Qualified superclass constructor invocations begin with a Primary
    expression.

    • They allow a subclass constructor to explicitly specify the newly
      created object’s immediately enclosing instance with respect to the
      direct superclass (§8.1.3). This may be necessary when the superclass
      is an inner class.

转载注明原文:java – 在范围内没有封闭类型的实例 - 代码日志