Java Generics
Keyword Description
? Wildcard type
extends T> Represents the upper bound of the type, indicating that the parameterized type may be T or a subclass of T
super T> Represents the type lower bound (called supertype qualification in Java Core), indicating that the parameterized type is the supertype (parent type) of this type, until Object
extends Example
static class Food{}
static class Fruit extends Food{}
static class Apple extends Fruit{}
static class RedApple extends Apple{}
List extends Fruit> flist = new ArrayList
// complie error:
// flist.add(new Apple() );
// flist.add(new Fruit());
// flist.add(new Object());
flist.add(null); // only work for null
List extends Frut> means "a list with any type inherited from Fruit". The compiler cannot determine the type held by List, so it cannot safely add objects to it. You can add null because null can represent any type. So the add method of List cannot add any meaningful elements, but it can accept assignments from existing subtypes List
Fruit fruit = flist.get(0);
Apple apple = (Apple)flist.get(0);
Since the placement is a type inherited from Fruit, the Fruit type can be safely taken out.
flist.contains(new Fruit());
flist.contains(new Apple());
When using the contains method in Collection, it accepts the Object parameter type without involving any wildcards, and the compiler allows it Call it like this.
super example
List super Fruit> flist = new ArrayList
flist.add(new Fruit());
flist.add(new Apple());
flist.add(new RedApple());
// compile error:
List super Fruit> flist = new ArrayList
List super Fruit> means "a list with any Fruit super type", list The type of is at least a Fruit type, so it is safe to add Fruit and its subtypes to it. Since the type in List super Fruit> may be the super type of any Fruit, it cannot be assigned to the subtype of Fruit Apple's List
// compile error:
Fruit item = flist.get(0);
Because the type in List super Fruit> may be any super type of Fruit, the compiler cannot determine whether the object type returned by get is Fruit, or Fruit’s parent class Food or Object.
Summary
extends Can be used for return type qualification, but not for parameter type qualification.
super can be used for parameter type qualification, but cannot be used for return type qualification.
> Wildcards with super supertype qualification can be written to generic objects, and wildcards with extends subtype qualification can be read from generic objects.
For more articles related to Java generic wildcard extends and super, please pay attention to the PHP Chinese website!