gpt4 book ai didi

java - 该字段是模糊的,而它显然是隐藏的

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:51:51 24 4
gpt4 key购买 nike

我知道并完全同意通过接口(interface)共享常量被视为 bad practice ,但我没有选择这个实现。随便:

interface SuperClassConstants {
public static final String CONSTANT = "super";
}

interface SubClassConstants extends SuperClassConstants {
public static final String CONSTANT = "sub";
}

class SuperClass implements SuperClassConstants {
}

class SubClass extends SuperClass implements SubClassConstants {
public SubClass() {
System.out.println(CONSTANT);
// The field CONSTANT is ambiguous
}
}

为什么模棱两可?常数不是隐藏的吗?我以为 Java 会理解我期待 “sub”...

最佳答案

根据 JLS 9.3 :

If two fields with the same name are inherited by an interface because, for example, two of its direct superinterfaces declare fields with that name, then a single ambiguous member results. Any use of this ambiguous member will result in a compile-time error.

SubClassConstants中的字段CONSTANT隐藏了SuperClassConstantsCONSTANT。但是 SubClass 类可以访问这两个 CONSTANT,因为它实际上实现了这两个接口(interface)。

您可以通过指定接口(interface)名称来消除歧义:

System.out.println(SubClassConstants.CONSTANT);

另请阅读 JLS 6.5.6.1 :

If an expression name consists of a single Identifier, then there must be exactly one declaration denoting either a local variable, parameter, or field visible (§6.4.1) at the point at which the Identifier occurs. Otherwise, a compile-time error occurs.

关于java - 该字段是模糊的,而它显然是隐藏的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17430339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com