上界通配符和下界通配符

public static void main(String[] args) {
        /*
            Object:超级父类!
            User:用户类!
            Student、Teacher:是User的子类!
            上界通配符:无法进行数据存储的!
            ? extends User:?是User的子类!  --> Teacher或者Student
            泛型:参数化类型!  --> 只能传递一个数据类型!
            取值:可以使用同一个类型将数据提取出来!
         */
        List<? extends User> users = new ArrayList<>(10);
        users.add(null);
        //取值
        User user = users.get(0);
        System.out.println(user);
        /*
            下界通配符
            ? super User:是User的父类!  ? 是Object!
            ? super Student:
         */
        List<? super User> users2 = new ArrayList<>(10);
        users2.add(new Student("123", "123"));
        users2.add(new Teacher("321", "321"));
        //取值
        Object object = users2.get(0);
        if (object instanceof Student) {
            Student student = (Student) object;
            System.out.println(student);
        } else if (object instanceof Teacher) {
            Teacher teacher = (Teacher) object;
            System.out.println(teacher);
        }
    }
posted @ 2022-12-12 10:20  Liku007  阅读(50)  评论(0编辑  收藏  举报