2 回答

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
您實(shí)際上不需要覆蓋/復(fù)制子類中的任何內(nèi)容。
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貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用泛型并保留relatives在父類中。此外,您應(yīng)該注意保留意外的修改:
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);
}
}
添加回答
舉報(bào)