Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java Generic Type parameter extend another Type parameter and additional bounded type?

I am creating a generic class (TestGeneric) with 2 type parameter (TAnimal and TMammal), with the 2nd type parameter (TMammal) extending the 1st type parameter (TAnimal) and another type (Mammal).

public class TestGeneric<TAnimal extends Animal, TMammal extends TAnimal & Mammal> { .. }

where

public interface Animal { ... }

public class Mammal implements Animal { ... }

I am getting this Java problem:

Cannot specify any additional bound Mammal when first bound is a type parameter.

If I swap the bounded type TAnimal & Mammal around,

public class TestGeneric<TAnimal extends Animal, TMammal extends Mammal & TAnimal> { .. }

I am getting another Java problem:

The type TAnimal is not an interface; it cannot be specified as a bounded parameter.

Is there anyway to overcome the above mentioned limitation in Java?

I am using Java 1.8-172.

like image 409
ndlianke Avatar asked Jun 09 '26 04:06

ndlianke


1 Answers

You can't use multiple bounds if one of the bounds is a type parameter.

Additionally, when using multiple bounds, the first one can be a class or an interface, and the remaining can only be interfaces. This stems from the fact that Java does not support multiple inheritance, so listing multiple classes is the same as listing only the furthest subclass.

To make it work, you either need to write the code like this:

public class TestGeneric<TAnimal extends Animal, TMammal extend Mammal & Animal> { }

Or, because Mammal implements the Animal interface anyway:

public class TestGeneric<TAnimal extends Animal, TMammal extends Mammal> { }
like image 106
Daniel Rauf Avatar answered Jun 11 '26 18:06

Daniel Rauf