繁体   English   中英

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

[英]overriding with different return types (generic collections)

请帮助我解决以下问题:

  1. Cat类必须扩展Animal (保持继承);
  2. Animal.getAll()必须返回所有动物(猫,狗等),而Cat.getAll()必须仅返回猫(不要更改签名)。

我尝试并失败并The return type is incompatible with Animal.getAll()错误The return type is incompatible with Animal.getAll()第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>();
    }
}

将第2行更改为:

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

它会工作。 有关更多信息,请参见泛型中的Java通配符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM