那些年路过的风景 2015-01-31 02:00 采纳率: 0%
浏览 1854

泛型限定[下限]super的使用报错,大神求解释!!!

 import java.util.*;
class Fan4Demo
{
    public static void main(String[] args)
    {
        ArrayList<Person> al = new ArrayList<Person>();
        al.add(new Person("Lisi1",1));
        al.add(new Person("Lisi2",2));
        al.add(new Person("Lisi3",3));
        print(al);
        ArrayList<Student> al2 = new ArrayList<Student>();
        al2.add(new Student("XiaoMing1",1));
        al2.add(new Student("XiaoMing2",2));
        al2.add(new Student("XiaoMing3",3));
        print(al2);
    }
    public static void print(ArrayList<? super Student> al) //传说中的泛型限定[下限],此处可以传入Student及Student类的父类型
    {
        Iterator<? super Student> it = al.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next().getName());//此处报错
        }
    }
}

class Person
{
    private String name;
    private int age;
    Person(String name,int age)
    {
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
}

class Student extends Person
{
    public Student(String name,int age)
    {
        super(name,age);
    }
}

图片说明

说说我的理解吧:? super Student 即:此处 ? 可以是Student类型或是Student类型的父类,那么问题来了,Object也是Student类的父类呀!!!那么.getName()方法就无法调用。但问题又来了,如果是这样的话,那么泛型限定的下限局限性也太大了,直接到了Object级别,自此非Object类的方法统统不能用。。。
这个只是我个人的理解不知道对不对,求大神再此不吝赐教解释下,谢谢!!!

  • 写回答

6条回答 默认 最新

  • bdmh 移动开发领域优质创作者 2015-01-31 02:22
    关注

    System.out.println(((Person)it.next()).getName());

    转型,因为不知道it.next()是什么

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?