views:

44

answers:

2

Hi,

Simple Java generics question: I have two classes - one of which uses generics to define its type, the other which extends this class providing a concrete type.

public class Box<Item> {
    ...
}


public class Toolbox extends Box<Tool>{
    ...
}

Given that Toolbox extends Box providing a Tool as the actual type for the generic placeholder, I would have thought it should be possible to do something like this:

Box<Tool> box = new Box();

Toolbox toolbox = box; 

However, it seems this causes a type-mismatch. Why is this?

+6  A: 

It's not really a generics issue. Your problem is that you're assigning an object of a less specific type to a variable of a more specific type.

You'd have the same problem if you tried to assign an Object to a String variable, even though String extends Object.

You should, however, be able to write Box<Tool> box = new Toolbox(); with the class structure given. Just not the other way around.

Michael Myers
Of course. Cheers... having a bit of a blonde moment today ;)
Jay Shark
A: 

Box<Item> is the unbound generic type. Box<Tool> is a particular bound version of that same generic type. Toolbox is a subclass of Box<Tool> and thus is a discrete type from Box<Tool>.

Kirk Woll