覆盖不同的返回类型(通用集合)

时间:2014-06-19 14:48:04

标签: java generics collections

请帮我解决以下问题:

  1. class Cat必须扩展Animal(保持继承);
  2. Animal.getAll()必须归还所有动物(猫,狗等),Cat.getAll()必须只返回猫(不要改变签名)。
  3. 我在第8行尝试了失败,错误The return type is incompatible with Animal.getAll()

    class Animal {
        public static List<Animal> getAll() {
            return new ArrayList<Animal>();
        }
    }
    
    class Cat extends Animal {
        public static List<Cat> getAll() {
            return new ArrayList<Cat>();
        }
    }
    

1 个答案:

答案 0 :(得分:1)

将第2行更改为:

public static List<? extends Animal> getAll() {

它会起作用。 有关详细信息,请参阅Java Wildcards in Generics

相关问题