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
,因此它应该能够appConst
在App.this
上下文中访问.
此代码失败,出现以下编译错误:
错误:无法从静态上下文引用非静态变量appConst
为什么?
原因是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中仅保持不变.
归档时间: |
|
查看次数: |
974 次 |
最近记录: |