2

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.

Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
Phuc Bui
  • 59
  • 1
  • 6

2 Answers2

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.

Peter Bratton
  • 6,302
  • 6
  • 39
  • 61
1

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.

DevdattaK
  • 198
  • 9
  • Note that the `? super CatFish` is not precisely a *type parameter* of the method, it's a wildcard for the type parameter of the method's (regular) *parameter*. Lower bounds on type parameters, strictly speaking, aren't allowed, as the other answer states. – Anakhand Mar 30 '20 at 14:06