在范围内没有封闭类型的实例 [英] no enclosing instance of type... in scope

查看:1631
本文介绍了在范围内没有封闭类型的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我调查java内部类。

I investigate java inner classes.

我写的例子:

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调用它:

I invoke it from main using following string:

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

我看到编译错误:

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

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

Can you explain me this situation?

UPDATE

推荐答案

Inner 是一个内部类。它只能在包含 Inner 类定义的类的封闭实例时创建。

Inner is an inner class. It can only be created when there is an enclosing instance of the class containing the Inner class definition.

但是,你已经创建了一个 static 嵌套类,嵌套,它从这个类扩展而来。当您尝试调用超级构造函数时

However, you've created a static nested class, Nested, which extends from this class. When you try to invoke the super constructor

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

它将失败因为超级构造函数,对于 Inner ,取决于 Outer 的实例,它不存在于 static 上下文中嵌套类。 Jon Skeet提供解决方案。

it will fail because the super constructor, for Inner, depends on an instance of Outer, which doesn't exist in the static context of the Nested class. Jon Skeet provides a solution.

对解决方案的解释出现在JLS 此处

An explanation of the solution appears in the JLS here.


超类构造函数调用可以细分:

Superclass constructor invocations may be subdivided:


  • 不合格的超类构造函数调用以关键字
    super开头(可能以显式类型参数开头)。

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

合格的超类构造函数调用以主
表达式开头。


  • 它们允许子类构造函数显式指定新的
    创建的对象,它是关于
    直接超类(第8.1.3节)的立即封闭实例。当超类
    是内部类时,这可能是必要的。

  • 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.

这篇关于在范围内没有封闭类型的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆