Junior — Middle
Can you explain the concept of inheritance when using generics?
sobes.tech AI
Answer from AI
In Java, generics do not support inheritance of types directly, meaning, for example, List<Dog> is not a subclass of List<Animal>, even if Dog inherits from Animal. This is because generics are invariant by default.
To address this issue, covariant and contravariant restrictions are used with wildcards:
List<? extends Animal>— covariant type, allows reading elements as Animal, but prohibits adding new elements.List<? super Dog>— contravariant type, allows adding Dog objects and its subclasses, but reading returns Object.
Example:
class Animal {}
class Dog extends Animal {}
List<Dog> dogs = new ArrayList<>();
List<? extends Animal> animals = dogs; // can read as Animal
Animal a = animals.get(0); // OK
// animals.add(new Dog()); // Compilation error
Thus, inheritance with generics is controlled through wildcards, not through direct inheritance of parameterized types.