我正在努力实现下一个目标:

上级:

public class Animal {
    private List<Animal> relatives;

    public List<Animal> getRelatives() {
        return relatives;
    }

    public void setRelatives(List<Animal> relatives) {
        this.relatives = relatives;
    }
}


儿童:

public class Dog extends Animal {
    private List<Dog> relatives;

    public List<Dog> getRelatives() {
        return relatives;
    }

    public void setRelatives(List<Dog> relatives) {
       this.relatives = relatives;
    }
}


但是由于某种原因,我收到了方法冲突的错误消息。如果不使用泛型类型,继承甚至有可能实现吗?

最佳答案

您实际上不需要重写/复制子类中的任何内容。

class Animal<Relative extends Animal<?>> {
  private List<? extends Relative> relatives;

  public List<? extends Relative> getRelatives() {
    return relatives;
  }

  public void setRelatives(List<? extends Relative> relatives) {
    this.relatives = relatives;
  }
}

class Dog extends Animal<Dog> {}

10-01 23:09