HoldYourWaffle
HoldYourWaffle

Reputation: 85

Generic argument 'extends' multiple classes

I have a question about generic arguments, this is the code I have:

public <T extends Renderable, Box> void setBackBox(T bb) {
    ...
}

As you see you can give as parameter bb an object that extends Box & Renderable. But eclipse gives the following waring: 'The type parameter Box is hiding the type Box'.

How can I fix this/work around it?

Upvotes: 5

Views: 15318

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62854

Here, you're defining two type-parameters:

  • T extends Renderable
  • Box

Box is the alias of the second method-scoped type-parameter and if you have another one with the same name (class-scoped), the method-scoped one will hide it. That's why Eclipse throws a warning.

If you want T to extend both Renderable and Box, you have to do:

public <T extends Renderable & Box> void setBackBox(T bb)

Also note that when your type-parameter(s) extend multiple types, you're allowed to use one class, which has to be first in the list. For example, if Box is a class, the correct definition would be:

public <T extends Box & Renderable> void setBackBox(T bb)

Upvotes: 9

Eran
Eran

Reputation: 393771

Here you defined Box to be a generic type parameter, which hides the Box class/interface :

public <T extends Renderable, Box> void setBackBox(T bb)

If Box is an interface that should be a bound of T :

public <T extends Renderable & Box> void setBackBox(T bb)

If Box is a class that should be a bound of T :

public <T extends Box & Renderable> void setBackBox(T bb)

If both Box and Renderable are classes, they can't both be type bounds of T. Only the first type bound can be a class.

Upvotes: 7

Related Questions