How to access an interface's field (which is by default public, static and final) using the implementing class's instance (this
or super
or instanceName if possible) if the field is hidden?
package mypack;
public interface MyInterface {
String str = "MyInterface.str";
String inheritanceTest = "inherited";
}
The field that i want to access is str
The other field inheritanceTest
is to prove that interface fields are in fact inherited (unlike interface static methods)
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;
}
}
Notes
I know that it is discouraged to access static members using an instance instead of accessing it statically (
Type.staticMemberNameOrSignature
).As shown, static interface methods are not inherited while static interface fields are inherited.
Non commented lines do not generate any compile-time errors.
Commented lines which are trying to assign a value to the variable
result
are the ones generating compile-time errors (Added to the line)I am not asking about how to access the interface field statically.
Clarifying The Question
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?