2015-10-15 70 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