关于Java泛型的小问题

itmgll 2011-12-30 04:09:23
为什么下面两句不能通过编译:
ArrayList<Dog> dogs = new ArrayList<Animal>();
ArrayList<Animal> animals = new ArrayList<Dog>();

其中,Dog是Animal的子类
...全文
126 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
我爱荤菜 2012-01-06
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 sunnykid5200 的回复:]
楼主问的意思跟接口没有任何关系,
就算用接口的话List<Animal> dogs = new ArrayList<Dog>();还是会编译报错的。

楼主只是想知道为什么父子关系的类不能够作为泛型实例化。

泛型只是指定存储对象的类型,ArrayList<T> animals = new ArrayList<T>();必须是一致的。
[/Quote]有道理
我爱荤菜 2012-01-06
  • 打赏
  • 举报
回复
ArrayList<Dog> dogs = new ArrayList<Animal>();
出问题的它,Animal是父类,
ArrayList<Animal> dogs = new ArrayList<Dog>();
就可以了
sunnykid5200 2012-01-06
  • 打赏
  • 举报
回复
楼主问的意思跟接口没有任何关系,
就算用接口的话List<Animal> dogs = new ArrayList<Dog>();还是会编译报错的。

楼主只是想知道为什么父子关系的类不能够作为泛型实例化。

泛型只是指定存储对象的类型,ArrayList<T> animals = new ArrayList<T>();必须是一致的。

ivan_ou 2011-12-30
  • 打赏
  • 举报
回复
如果你这样写就可以List<Dog> dogs = new ArrayList<Dog>();
因为ArrayList实现了List接口
ivan_ou 2011-12-30
  • 打赏
  • 举报
回复
ArrayList<Dog> dogs = new ArrayList<Dog>();中的Dog只是指定ArrayList中存储对象的类型,并不存在什么子父关系

567

社区成员

发帖
与我相关
我的任务
社区描述
英特尔® 边缘计算,聚焦于边缘计算、AI、IoT等领域,为开发者提供丰富的开发资源、创新技术、解决方案与行业活动。
社区管理员
  • 英特尔技术社区
  • shere_lin
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧