Java : 访问隐藏接口字段
Java : Accessing Hidden Interface Field
如何使用实现 class 的实例(this
或 super
或instanceName(如果可能)如果该字段被隐藏?
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
) 的 class?
Is it possible to access an interfaces field that have been hidden by the implementing class using an instance (instance keywords like this or super) of the class?
是的。不使用 this 或 super,只需使用接口名称即可访问它。
MyInterface.str
如何使用实现 class 的实例(this
或 super
或instanceName(如果可能)如果该字段被隐藏?
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
) 的 class?
Is it possible to access an interfaces field that have been hidden by the implementing class using an instance (instance keywords like this or super) of the class?
是的。不使用 this 或 super,只需使用接口名称即可访问它。
MyInterface.str