简体   繁体   中英

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. This is because we need to know the entries to the VTBL at compile time and each template type is compiled separately.

In Java however I understand that the generic type is compiled only once which can enable overriding methods of a generic class. Is this true?

If so, Does this design choice makes?

Java doesn't have template classes. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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