从内部接口的默认方法访问实例变量

Bor*_*der 5 java static java-8

鉴于我们现在有default上的方法,interface在Java中8,有没有我们可以访问实例方法从父类中的一个内(非任何方式static)interface,例如是这样的:

public class App {

    int appConst = 3;

    public interface MyInstanceInterface {

        default int myAppConst() {
            return appConst;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

interface不是static,因此它应该能够appConstApp.this上下文中访问.

此代码失败,出现以下编译错误:

错误:无法从静态上下文引用非静态变量appConst

为什么?

Bor*_*der 8

原因是JLS§8.5.1:

成员接口是隐式静态的(第9.1.1节).允许声明成员接口冗余地指定static修饰符.

内心interface永远不会是非static.声明:

public class App {

    ...      

    public interface MyInterface {

        ...

    }
}
Run Code Online (Sandbox Code Playgroud)

完全等同于:

public class App {

    ...      

    public static interface MyInterface {

        ...

    }
}
Run Code Online (Sandbox Code Playgroud)

注意:这一直是这种情况,并且在Java 8中仅保持不变.