如果字段隱藏,如何使用實現類的實例(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