2 回答
TA贡献1921条经验 获得超9个赞
您实际上不需要覆盖/复制子类中的任何内容。
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> {}
TA贡献1811条经验 获得超6个赞
您可以使用泛型并保留relatives在父类中。此外,您应该注意保留意外的修改:
public class Animal<T extends Animal<?>> {
private final List<T> relatives = new ArrayList<>();
public final List<T> getRelatives() {
return relatives.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(relatives);
}
public final void addRelative(T relative) {
Objects.requireNonNull(relative);
relatives.add(relative);
}
}
public class Dog extends Animal<Dog> {
// just for test
public List<Dog> getRelativesDogs() {
return super.getRelatives();
}
// just for test
public void addRelativeDog(Dog dog) {
super.addRelative(dog);
}
}
添加回答
举报