【发布时间】:2016-01-14 10:05:29
【问题描述】:
如果字段被隐藏,如何使用实现类的实例(this 或 super 或 instanceName,如果可能)访问接口的字段(默认为 public、static 和 final)?
package mypack;
public interface MyInterface {
String str = "MyInterface.str";
String inheritanceTest = "inherited";
}
我要访问的字段是str
另一个字段inheritanceTest是为了证明接口字段其实是继承的(不像接口静态方法)
package mypack;
public class Child implements MyInterface {
// Hiding the field
String str = "Child.str";
// Access test.
public String getParentStr() {
String result = "";
// result = MyInterface.super.str; // No enclosing instance of the type MyInterface is accessible in scope
// result = super.str; //str cannot be resolved or is not a field
return result;
}
// A method to check if the field is inherited or not.
public String getInheritedString() {
return this.inheritanceTest;
}
}
备注
我知道不鼓励使用实例访问静态成员而不是静态访问它 (
Type.staticMemberNameOrSignature)。如图所示,静态接口方法不被继承,而静态接口字段被继承。
没有注释的行不会产生任何编译时错误。
试图为变量
result赋值的注释行是产生编译时错误的行(添加到该行)我不是询问如何静态访问界面字段。
澄清问题
是否可以访问已被实现类使用类的实例(this 或super 等实例关键字)隐藏的接口字段?
【问题讨论】:
-
return MyInterface.str; -
它是一个接口这一事实并不重要。
-
@SotiriosDelimanolis 问题已更新。
-
答案还是一样。 JLS 的报价涵盖所有选项。其中只有两个与接口相关,完全限定名称和转换为接口。
-
据我所知,JLS 是对的。