This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Extending Generics to Subclasses Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Extending Generics to Subclasses" Watch "Extending Generics to Subclasses" New topic

Extending Generics to Subclasses

Brendan Thompson

Joined: Apr 27, 2012
Posts: 21
Hi I have a question regarding how to restrict a subclass to only implementing some of the superclass' generics.

GenericOrder can take ComputerPart, Peripheral, Service, Cheese, and Fruit classes. I want the subclass ComputerOrder to only be able to take ComputerPart, Peripheral, and Service classes. Eclipse gives me a warning with the code I've got now so I'm not sure if I have it right or not. This is the Eclipse warning:

Multiple markers at this line
- The type parameter ComputerPart is hiding the type
- The type parameter Service is hiding the type Service
- The type parameter Peripheral is hiding the type Peripheral

Matthew Brown

Joined: Apr 06, 2010
Posts: 4541

I don't think you've got the right idea about generics. This line:
doesn't create a class restricted to those 5 types. It declares a class that has 5 generic types, with ComputerPart, Peripheral, Service, Cheese, Fruit just used as the generic placeholders. Here it's not referring to the actual classes ComputerPart etc. You might as well have written:
And following on from that, any class that extends GenericOrder needs to provide classes for all 5 generic types (or be generic itself).

There's no way using generics to have a class operating on 5 specific random classes and no others. That's not what they are for.
Brendan Thompson

Joined: Apr 27, 2012
Posts: 21
Thanks for clearing that up. Generics are still a bit confusing to me so I'll try and read a bit more about them.
I agree. Here's the link:
subject: Extending Generics to Subclasses
It's not a secret anymore!