views:

225

answers:

2

I have a class Foo with subclass SubFoo, a collection class FooListing.

I want to create a generic FooListing<T> where T is either Foo or a subclass of Foo

From the wording of the documentation (under 'Wildcards'), it sounds like

public class FooListing<T extends Foo> { ... }

...would let me use FooListing<SubFoo>, but not FooListing<Foo>, is this correct?

+3  A: 

No, you're already fine - what you've got allows T to be Foo.

I've tried to find the relevant bit of the spec, but unfortunately it's extremely opaque :( It definitely works though!

Jon Skeet
Agreed, it works in practice! I just couldn't find anyone explicitly stating this one way or another..
brass-kazoo
+3  A: 

(This should be a comment to the first answer, I think.)

Yes, this will work. The generic T will become a Foo when compiled. So you can use any T which extends Foo (or even Foo itself) because of casting rules.

In case you don't set any supertype for the generic type setting, it will become an Object when compiled. Because, then you want to allow each and every type for your class, so it has to be castable to any type and only Object is able to serve this.

Hurix