2015-10-15 101 views
1

如果字段隱藏,如何使用實現類的實例(thissuper或實例名稱,如果可能的話)訪問接口的字段(默認爲公共,靜態和最終)?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; 
    } 
} 

筆記

  1. 我知道使用實例訪問靜態成員而不是靜態訪問靜態成員是不鼓勵的(Type.staticMemberNameOrSignature)。

  2. 如圖所示,當靜態接口字段被繼承時,靜態接口方法不會被繼承。

  3. 非註釋行不會產生任何編譯時錯誤。

  4. 評論它正試圖賦值給變量result線是那些產生編譯時錯誤(添加到線)

  5. 詢問如何訪問接口場靜態

澄清問題

是否有可能訪問已隱藏通過使用類的一個實例(例如關鍵字,如thissuper)實現類的接口字段?

+2

'return MyInterface.str;' –

+0

它是一個接口的事實並不重要。 –

+0

@SotiriosDelimanolis問題已更新。 – naaz

回答

1

是否有可能通過類的實例(類似於this或super的實例)訪問被實現類隱藏的接口字段?

是。而不是使用這個或超級,只需使用接口名稱來訪問它。

MyInterface.str 
+0

更新了問題。 – naaz