通配符extends和super的使用小例子

一、我们要达到的目的

我们要通过使用extends和super两个关键字

做到:

使一个类的入参满足我们限定的范围、也就说我们可以给入参(泛型)指定范围。

使入参全部都是某个类的子类。

二、具体的实现

场景

对于集合(ArrayList)的存取

继承树

Animal -> Cat ->BlueCat ->BlueSmallCat

第一种实现(在被调用类中限定)

在被操作的类上加通配符

import java.util.ArrayList;

public class BrrayList<T extends Animal> extends ArrayList<T> {
    
    
}
public class Main {
    
    
    public static void main(String[] args) {
    
    
        BrrayList<BlueCat> brrayList = new BrrayList<>();

        BlueCat blueCat = new BlueCat();
        blueCat.setName("blueCat");

        brrayList.add(blueCat);

        System.out.println(brrayList.get(0).getName());
    }

}

第二种实现(在调用类中限定)

public class Main {
    
    
    public static void main(String[] args) {
    
    
        ArrayList<? super Cat> arrayList = new ArrayList<>();

        BlueSmallCat blueSmallCat = new BlueSmallCat();
        blueSmallCat.setName("blueSmallCat~~");

        arrayList.add(blueSmallCat);

        Object object = arrayList.get(0); //强制类型转换 编译器根据通配符无法直接识别参数的具体类型
        blueSmallCat = (BlueSmallCat) object;

        System.out.println(blueSmallCat.getName());

    }

}

猜你喜欢

转载自blog.csdn.net/GBS20200720/article/details/121188839
今日推荐