简体   繁体   English

是否可以重写Java中通用类的方法?

[英]Is it possible to override a method of a generic class in Java?

I know that in C++ there is no such thing as a virtual templates function. 我知道在C ++中没有虚拟模板函数之类的东西。 This is because we need to know the entries to the VTBL at compile time and each template type is compiled separately. 这是因为我们需要在编译时知道VTBL的条目,并且每种模板类型都是单独编译的。

In Java however I understand that the generic type is compiled only once which can enable overriding methods of a generic class. 但是,在Java中,我理解泛型仅被编译一次,因此可以启用泛型类的重写方法。 Is this true? 这是真的?

If so, Does this design choice makes? 如果是这样,此设计选择是否可行?

Java doesn't have template classes. Java没有模板类。 Instead, it has Generics, which are regular Java classes that have additional type information at compile-time that allows the compiler to perform type-safety checks. 相反,它具有泛型,泛型是常规Java类,在编译时具有附加的类型信息,使编译器可以执行类型安全检查。 Once those checks are done, the information about the generic types is "erased", and the compiled class looks like any other class. 一旦完成这些检查,就将“擦除”有关泛型类型的信息,并且已编译的类将与其他任何类一样。

Any non final, non private, non static method can be overridden in a sub-class, whether it is generic or not. 可以在子类中重写任何非最终,非私有,非静态方法,无论该方法是否通用。 This work because the type is actually a reference in every case. 这项工作是因为类型实际上在每种情况下都是引用 When you change the type, you are just changing the type of the reference. 更改类型时,您只是在更改引用的类型。

BTW All non-static methods are "virtual" in Java. 顺便说一句,所有非静态方法在Java中都是“虚拟”的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM