如果字段隐藏,如何使用实现类的实例(this
或super
或实例名称,如果可能的话)访问接口的字段(默认为公共,静态和最终)?Java:访问隐藏接口字段
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问题已更新。 – naaz