猿问

Java继承。父级有父级列表,子级必须有子级列表。如何?

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


家长:


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;

    }

}

但由于某种原因,我收到方法冲突的错误。这是否可以通过继承而不使用泛型类型来实现?


婷婷同学_
浏览 104回答 2
2回答

郎朗坤

您实际上不需要覆盖/复制子类中的任何内容。class Animal<Relative extends Animal<?>> {&nbsp; private List<? extends Relative> relatives;&nbsp; public List<? extends Relative> getRelatives() {&nbsp; &nbsp; return relatives;&nbsp; }&nbsp; public void setRelatives(List<? extends Relative> relatives) {&nbsp; &nbsp; this.relatives = relatives;&nbsp; }}class Dog extends Animal<Dog> {}

杨魅力

您可以使用泛型并保留relatives在父类中。此外,您应该注意保留意外的修改:public class Animal<T extends Animal<?>> {&nbsp; &nbsp; private final List<T> relatives = new ArrayList<>();&nbsp; &nbsp; public final List<T> getRelatives() {&nbsp; &nbsp; &nbsp; &nbsp; return relatives.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(relatives);&nbsp; &nbsp; }&nbsp; &nbsp; public final void addRelative(T relative) {&nbsp; &nbsp; &nbsp; &nbsp; Objects.requireNonNull(relative);&nbsp; &nbsp; &nbsp; &nbsp; relatives.add(relative);&nbsp; &nbsp; }}public class Dog extends Animal<Dog> {&nbsp; &nbsp; // just for test&nbsp; &nbsp; public List<Dog> getRelativesDogs() {&nbsp; &nbsp; &nbsp; &nbsp; return super.getRelatives();&nbsp; &nbsp; }&nbsp; &nbsp; // just for test&nbsp; &nbsp; public void addRelativeDog(Dog dog) {&nbsp; &nbsp; &nbsp; &nbsp; super.addRelative(dog);&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答