Home  >  Article  >  Java  >  Upper bound (extend) and lower bound (super) in java generics

Upper bound (extend) and lower bound (super) in java generics

(*-*)浩
(*-*)浩forward
2019-08-22 15:54:343822browse

Upper bound (extend) and lower bound (super) in java generics

Definition of upper and lower bounds in generics

Upper bound

Lower bound< ? super Apple>

Characteristics of upper bounds and lower bounds

The upper bound list can only be get, not add (to be precise, it cannot add anything other than null) Objects, including Object)

The lower bound list can only be added, but not get

import java.util.ArrayList;
import java.util.List;
 
class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}
 
public class CovariantArrays {
  public static void main(String[] args) {
	//上界
    List<? extends Fruit> flistTop = new ArrayList<Apple>();
    flistTop.add(null);
    //add Fruit对象会报错
    //flist.add(new Fruit());
    Fruit fruit1 = flistTop.get(0);
 
	//下界
    List<? super Apple> flistBottem = new ArrayList<Apple>();
    flistBottem.add(new Apple());
    flistBottem.add(new Jonathan());
    //get Apple对象会报错
    //Apple apple = flistBottem.get(0);
  }
}

The reason for these characteristics

Upper bound

Lower bound means that all parent classes of Apple, including Fruit, can be traced back to the ancestor Object. Then when I add, I can't add Apple's parent class, because I can't determine which parent class is stored in the List. But I can add Apple and its subclasses. Because no matter what type my subclass is, it can be transformed upward to Apple and all its parent classes or even to Object. But when I get it, there are so many parent classes of Apple. What should I use to continue it? Except for Object, I can’t catch anything else.

So, in the final analysis, it can be expressed in one sentence, that is, the compiler can support upward transformation, but does not support downward transformation. Specifically, I can assign the Apple object to a reference to Fruit, but if I assign the Fruit object to a reference to Apple, I must use cast

The above is the detailed content of Upper bound (extend) and lower bound (super) in java generics. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete