0

In the code below, class Team is provided with generics,

public class Team<T extends Player>
{

declaring another type League with generics

public class League<T extends Team>
{

The question: From the following valid code:

League<Team<FootballPlayer>> league = new League<>();

I infer that Team<FootballPlayer> extends Team, is that true? Isn't it the case that any Team<T> is a subclass of Object (typically) but not Team?

Profess Physics
  • 317
  • 4
  • 11
  • Why do you infer that? – Eran Jul 02 '17 at 09:37
  • Don't use raw types. The definition of League should be `class League

    >`. You shouldn't even ask yourself if `Team` extends Team. Team is a raw type, and you shouldn't use raw types. They ruin the whole point of generics.

    – JB Nizet Jul 02 '17 at 09:40
  • JB Nizet thank you, but then why is the previous code valid? I mean Team in how is java dealing with it, what is it ~~! how is it validating Team – Profess Physics Jul 02 '17 at 09:43
  • 2
    If you have a variable `gt` of the generic type Team, and a variable `rt` of the raw type Team, then `rt` is assignable to `gt` and vice-versa, because using raw types basically says to the compiler: "I don't care about the generic types. Go back to pre-generics mode of compilation". For more information, read the JLS. Also see https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – JB Nizet Jul 02 '17 at 09:50
  • Thank you for being so helpful. – Profess Physics Jul 02 '17 at 09:55
  • 1
    There's subtyping among generic types without having subclasses. `Team` is a *subtype* of `Team`, but not a *subclass* of `Team`. The use of the `extends` keyword in type variable bounds is just a reuse of a keyword. The type variable doesn't literally extend the class specified in the bound. – Radiodef Jul 02 '17 at 14:45

1 Answers1

1

Team<FootballPlayer> does NOT extend Team. Generics and inheritence are two different concepts. In Java, Generics are used by the compiler to ensure type safety when accpeting method arguments, instance variables and such. Inheritence is used both by the compiler and the run time VM to enable features such as polymorphism. A class may have generic parameter and also extend another unrelated class.

from your code, I infer that FootballPlayer extends Player but Team<?> does not extend Team The specification <T extends Team> (as mentioned in comments, should be <T extends Team<?>>) means that when the compiler sees this line in League class:

public void add(T team)

it will accpet invocations of add with argument of type Team or any of its subclasses. any other case will cause compile error.

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47