【发布时间】:2020-04-24 11:29:29
【问题描述】:
我有一个名为 Team 的抽象类,从中派生出另外三个名为 FootballTeam、BasketballTeam 和 VolleyballTeam 的类。在基类中,我有一种计算两支球队比赛结果的方法,但我需要一种正确使用泛型的方法,以避免不同运动的球队相互对抗。我显然在这里做错了什么,但我无法弄清楚。
基类:
public abstract class Team<T extends Team<T>> {
protected String teamName;
protected Integer won = 0;
protected Integer lost = 0;
protected Integer tied = 0;
protected Integer played = 0;
public void matchResult(T opponent, Integer homeScore, Integer awayScore) {
if (homeScore > awayScore) {
won++;
} else if (homeScore < awayScore) {
lost++;
} else {
tied++;
}
played++;
if (opponent != null) {
opponent.matchResult(null, awayScore, homeScore);
}
}
}
派生类:
public class FootballTeam extends Team {
public FootballTeam(String teamName) {
super(teamName);
}
// code
}
public class BasketballTeam extends Team {
public BasketballTeam(String teamName) {
super(teamName);
}
// code
}
public class VolleyballTeam extends Team {
public VolleyballTeam(String teamName) {
super(teamName);
}
// code
}
另一种解决方案是在每个子类中实现 matchResult 方法,但这不符合 DRY 原则。
【问题讨论】:
-
public class FootballTeam extends Team<FootballTeam>.
标签: java generics inheritance