Generic Lower bounded Method

不羁岁月 提交于 2021-02-10 08:03:23

问题


Let's say I have the following classes Animal, Fish, and CatFish.

CatFish extends Fish and Fish extends Animal.

There is a generic class called MyPets, which has a type parameter (generic) called T, and that will be parameterized with the above classes' objects.

My question is, how do I create a lower bounded method in D that will take any objects that is a PARENT class of the CatFish class.


回答1:


You can't.

TL;DR:

Type parameters can have several bounds, like in class Box {...} . But a type parameter can have no lower bound, that is, a construct such as class Box {...} is not permitted. Why not? The answer is: it is pointless because it would not buy you anything, were it allowed.




回答2:


You Can.

Its just the the use of such Lower Bound Generics is debatable and not encouraged. basic use :

public void treatAnimalWhichIsCatFishOrSuperType(Animal<? super CatFish> catFishOrParent){
}

There are other alternatives when you want to return an instance of a generic type from this method, but you can find that in above link.



来源:https://stackoverflow.com/questions/15536403/generic-lower-bounded-method

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