Daniel Bingham
Daniel Bingham

Reputation: 12914

Can a Java Generic Using a Bound Parameter be Instantiated with its Upper Bound?

For example:

class MyClass<T extends MyClass2> {
    // Do stuff...
} 

Then later:

MyClass<MyClass2> myClass = new MyClass<MyClass2>();

Does this work? My coworker's hunch is no, but I can't find anything to confirm that for me and the documentation suggests perhaps.

Upvotes: 1

Views: 243

Answers (4)

helios
helios

Reputation: 13841

Yes, you can. T extends ClassX checks that ClassX.isAssignableFrom(T.class)).

super is the opossite, so you can use the bound class too.

And... you could program a test to find out :)

Upvotes: 2

Kylar
Kylar

Reputation: 9324

This works fine. I just wrote this:

public class MoreGeneric {
  public static void main(String[] args) {
    new MyClass1<MyClass2>();
   }


  public static class MyClass1<T extends MyClass2>{}
  public static class MyClass2{}
}

And it compiled fine.

Upvotes: 4

noah
noah

Reputation: 21519

Yep, that works just fine. Lower bounds are inclusive.

Upvotes: 2

anthares
anthares

Reputation: 11213

I don't see anything wrong. Even MyClass<MyClass> m = new MyClass<MyClass>(); should be valid expression (even useful, maybe).

Upvotes: 2

Related Questions