Home  >  Article  >  Java  >  Java generic wildcard extends and super

Java generic wildcard extends and super

高洛峰
高洛峰Original
2016-12-19 15:57:301406browse

Java Generics

Keyword Description

? Wildcard type

Represents the upper bound of the type, indicating that the parameterized type may be T or a subclass of 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 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 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 flist = new ArrayList();
flist.add(new Fruit());
flist.add(new Apple());
flist.add(new RedApple());

// compile error:
List flist = new ArrayList();

List 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 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 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn