Java generics
keyword Description? wildcard character type Extends t> represents the upper bound of a type, which indicates that a parameterized type may be a subclass of T or T. The super t> represents the lower bound of the type (called a supertype qualifier in the Java core), indicating that the parameterized type is a supertype of this type (the parent type) until the object
extends Sample
Class Food {
public static void Main (string[] args) {
list<? Extends t>
list<? Extends fruit> list=new arraylist<apple> ();
List.add (New Apple ());
List.add (New Object ());
List.add (NULL);
Fruit f=list.get (0);
Apple a= (apple) list.get (0);
}
}
Class Fruit extends food{}
Class Apple extends fruit{}
list<? Extends frut> means "with any list of inherited types from fruit", the compiler cannot determine the type that the list holds, so it is not safe to add objects to it. You can add null because null can represent any type. So the Add method of the list cannot add any meaningful elements, but you can accept an existing subtype list<apple> assignment.
Because the placement is a type inherited from fruit, the fruit type can be safely removed. List.contains (New Apple ());
List.contains (New Fruit ());
when using the Contains method in collection, the object parameter type is accepted, and no wildcard characters can be involved, and the compiler allows such a call. Super Example
Class Food {
public static void Main (string[] args) {
list<? Super fruit> List=new arraylist<fruit> ();
List.add (New Apple ());
List.add (New Fruit ());
}
}
Class Fruit extends food{}
Class Apple extends fruit{}
list<? Super fruit> represents "a list with any Fruit super type", and the type of the list is at least one Fruit type, so you can safely add Fruit and its subtypes to it. Apple a= (apple) list.get (0);
Summary
Extends can be used to return type qualification and cannot be used for parameter type qualification.
super can be used for parameter type qualification and cannot be used for return type qualification.
wildcard characters with super Super type qualification can be written to generic objects, and
wildcard characters with extends subtypes can be read to generic objects.