理解java泛型中的 上界extend 下界super


class Fruit {
    public int add(){
        return 0;
    }
}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}

class CovariantArrays {
    public static void main(String[] args) {
        //上界
        List<? extends Fruit> flistTop = new ArrayList<Apple>();
        flistTop.add(null);
        // flistTop.get(0).add();
        //add Fruit對象會報錯
        //flist.add(new Fruit());
        Fruit fruit1 = flistTop.get(0);

        //下界
        List<? super Apple> flistBottem = new ArrayList<>();
        flistBottem.add(new Apple());
        flistBottem.add(new Jonathan());
        flistBottem.forEach(a -> {
            if (a instanceof Jonathan) {
                System.out.println("a instanceof Jonathan"); //正確輸入
            }
        });
        //get Apple對象會報錯
        //Apple apple = flistBottem.get(0);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM