【问题标题】:Java : Accessing Hidden Interface Field [duplicate]Java:访问隐藏的接口字段
【发布时间】:2016-01-14 10:05:29
【问题描述】:

如果字段被隐藏,如何使用实现类的实例(thissuper 或 instanceName,如果可能)访问接口的字段(默认为 public、static 和 final)?

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 等实例关键字)隐藏的接口字段?

【问题讨论】:

  • return MyInterface.str;
  • 它是一个接口这一事实并不重要。
  • @SotiriosDelimanolis 问题已更新。
  • 答案还是一样。 JLS 的报价涵盖所有选项。其中只有两个与接口相关,完全限定名称和转换为接口。
  • 据我所知,JLS 是对的。

标签: java interface field


【解决方案1】:

是否可以使用类的实例(如 this 或 super 的实例关键字)访问已被实现类隐藏的接口字段?

是的。不要使用this或super,只需使用接口名称即可访问它。

MyInterface.str

【讨论】:

    猜你喜欢
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    相关资源
    最近更新 更多