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.
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> { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With