Java: extends 后有&是什么意思

看待一段代码,一个类的定义,其中<E extends Enum<?> & BaseEnum> 这里的这个&是什么意思?

public class EnumTypeHandler<E extends Enum<?> & BaseEnum> extends BaseTypeHandler<BaseEnum>
阅读 4.3k
2 个回答
package TypeVarMembers;
class C {
    public void mCPublic() {}
    protected void mCProtected() {}
    void mCPackage() {}
    private void mCPrivate() {}
}
interface I {
    void mI();
}
class CT extends C implements I {
    public void mI() {}
}
class Test {
    <T extends C & I> void test(T t) {
        t.mI(); // OK
        t.mCPublic(); // OK
        t.mCProtected(); // OK
        t.mCPackage(); // OK
        t.mCPrivate(); // Compile-time error
    }
}
The type variable T has the same members as the intersection type C & I, which in turn
has the same members as the empty class CT, defined in the same scope with equivalent
supertypes. The members of an interface are always public, and therefore always inherited`
(unless overridden). Hence mI is a member of CT and of T. Among the members of C, all
but mCPrivate are inherited by CT, and are therefore members of both CT and T.
If C had been declared in a different package than T, then the call to mCPackage would
give rise to a compile-time error, as that member would not be accessible at the point where
T is declared.

来自 The Java® Language Specification, Java SE 8 Edition $ 4.4 Type Variables P58~59

1楼正解
& 在java中是and的意思,在泛型的应用场景,含义基本不变。
public class EnumTypeHandler<E extends Enum<?> & BaseEnum> extends BaseTypeHandler<BaseEnum>
中的E extends Enum<?> & BaseEnum可以理解为 E extends (Enum<?> & BaseEnum),结合extends的含义,及E 为 Enum<?> 和 BaseEnum 的子类

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题