Generic class E with type parameter to be a subclass of E

Jia Zheng Lua :

I am relatively new to the concept of generics in Java and I cannot tell the difference between the 2 answers.

The question at hand is :
Suppose we have a generic class E and we want the type parameter to E to be a subClass of E. In other words, we allow E<F> only if class F is either E or inherits from E.

I have narrowed down the options to what is possible.

1. class E<T extends E>
2. class E<T extends E<T>>.

I believe that option 1 meet the specification for the question. However i am confused about option 2, what does it actually extend.

MC Emperor :

Well, option 1 actually uses a raw type.

You define E to have a parameter T, so E is a parameterized type. If you define T to extend E, you must also specify the type parameter of E, or else E is a raw type.

So the only "valid"1 option is option 2:

class E<T extends E<T>>

The Enum class is a well-known example of a recursive type parameter. See Java Enum definition.


1 Technically, the first option is also valid in the sense of syntactically correct. But raw types are only there for backward compabibility. New code should never contain raw types. See also What is a raw type and why shouldn't we use it?.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134340&siteId=1