2

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.

Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
Jia Zheng Lua
  • 91
  • 1
  • 7
  • You are attempting to parameterise a parent with knowledge of what its children are. This is abuse/misuse of inheritance. The parent should not care what its children are. – Michael Apr 17 '19 at 10:00

1 Answers1

3

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?.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130