问题
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