質問

I know and fully agree that sharing constants through interfaces is considered as a bad practice, but I didn't choose this implementation. Whatever:

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
    }
}

Why ambiguous? Isn't the constant hidden? I thought Java would have understood I was expecting "sub"...

役に立ちましたか?

解決

As per the 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.

The field CONSTANT in SubClassConstants has hidden the CONSTANT of SuperClassConstants. But the class SubClass has access to both the CONSTANT as it virtually implements both the interfaces.

You can remove the ambiguity by specifying the Interface name :

System.out.println(SubClassConstants.CONSTANT);

Also read 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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top