开发者

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

开发者 https://www.devze.com 2022-12-21 14:40 出处:网络
For example: class MyClass<T extends MyClass2> { // Do stuff... } Then later: MyClass<MyClass2> myClass = new MyClass<MyClass2>();

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.


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.


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


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


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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消