Why Wild Cards can't be used in generic class & method declaration?

一个人想着一个人 提交于 2019-12-13 04:41:48

问题


Declaration like this :

  class A<X extends Number & List> {  } 

is allowed.Whereas declaration like this is not allowed.

  class A<? extends Number & List> {  }

Is there any logical explanation about why Java restricts us to do that?

& what's the actual difference between

      <T extends Number>  
     & <? extends Number>?

回答1:


The whole point of a type parameter like T is so that you can use it as a type inside the class. What would a wildcard there even mean? If you can't use it anywhere, why have a type parameter at all?




回答2:


If you used <? extends Number & List>, then you wouldn't be able to do anything with the type parameter. It'd be completely useless.

Similarly, ? extends Number lets you deal with the special case when you don't need to refer to the type that extends number, and you don't need to give it a name.




回答3:


Generic class and interface declarations want type parameters, such as T or U. ? is a wildcard, better used for method parameters that are themselves generic:

class Foo<T extends Number & List> {
    void doStuff(List<T> items) {
        // ...
    }

    void doMoreStuff(List<? extends OutputStream> streams) {
        // ...
    }
}

doStuff() indicates that it wants to operate on a List<T> where T is the type parameter on class Foo. So:

class Weird extends Number implements List {
    //
}

Foo<Weird> f = new Foo<Weird>();
f.doStuff(...);   // wants a List<Weird>

If we called doMoreStuff() on f, we could hand it something of type List<OutputStream>, List<FilterOutputStream>, List<ByteArrayOutputStream>, etc.



来源:https://stackoverflow.com/questions/9914302/why-wild-cards-cant-be-used-in-generic-class-method-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!