您好,我需要帮助解决我遇到的下一个作业问题。
这只是问题的一部分,但我只需要这部分的帮助。
我想制作一个模拟奥运会的小系统。我想模拟三种运动:游泳、骑自行车和运行。我想使用四种类型的运动员,游泳运动员、自行车运动员、短跑运动员(分别可以参加游泳、自行车和运行比赛)以及可以参加所有三项比赛的 super 运动员(这是我遇到最多问题的运动员) 。每个运动员应该有一个compute()方法,它会随机生成10到20秒的运行时间、100到200秒的游泳时间和500到800秒的自行车时间,这个时间将用于阻止比赛的获胜者。
我的问题是如何模拟这个问题,使用什么样的类,它们之间的关系是什么。我需要一种方法来制作不同的游戏对象,例如 SwimGame,它仅包含 Swim 和 Super Athlete 的列表。
这是我现在的方法。
因此,我将拥有基本的抽象类 Athlete,而骑行者、运行者、游泳者和 super 运动员将从该类扩展。
我还将拥有 Game 抽象类,并且 SwimGame、CycleGame 和 RunningGame 将从这里扩展。每场比赛都会有参加比赛的运动员名单。
我怎样才能防止运行者被添加到游泳游戏中,以及类似的情况
当 superAthleat 可以参加所有 3 场比赛时,我将如何延长计算时间
一开始我以为我做了3个接口(interface):
interface swimInterface() {
public void calculateSwimTime();
}
interface runInterface() {
public void calculateRunTime();
}
interface cycleInterface() {
public void calculateCycleTime();
}
然后让 SwimmerAthlete 实现 SwimInterface,然后 runAthlete 实现 runInterface,cycleAthlete 实现 CycleInterface,最重要的是 superAthlete 实现 runInterface、swimmerInterface 和 CycleInterface,所以我会有这样的东西:
public abstract class Athlete {
...
// what should be here
}
public class SwimAthlete extends Athlete implements SwimInterface {
...
public void calculateSwimTime() {...}
}
public class RunAthlete extends Athlete implements RunInterface {
...
public void calculateRunTime() {...}
}
public class CylcleAthlete extends Athlete implements CycleInterface {
...
public void calculateCycleTime() {...}
}
public class SuperAthlete extends Athlete implements SwimInterface, CycleInterface, RunInterface() {
public void calculateSwimTime() {...}
public void calculateRunTime() {...}
public void calculateCycleTime() {...}
}
但是我还有很多其他问题: 如果我有这样的东西:
public class Game {
ArrayList<Athlete> listOfCompetitors;
public Game(){
listOfCompetitors = new ArrayList<Athlete>();
}
}
public class SwimGame extends Game {
// I could have something like this here
// how could I add only SwimAthlete and SuperAthlete here
// how to traverse the array of athletes and only call calculateSwimTime method.
}
// similar for other games.
如果您需要更多解释,我非常愿意讨论这个问题。
最佳答案
interface Sport
{
void compete();
}
abstract class Athlete implements Sport
{
String name;
int time = 0;
void setName(String name)
{
this.name = name;
}
void setTime(int time)
{
this.time = time;
}
String getName() { return name; }
int getTime() { return time; }
}
class Runner extends Athlete
{
Runner(String name)
{
setName(name);
}
@Override
public void compete()
{
int time = 10 + (int) (Math.random() * ((20d - 10d) + 1d));
setTime(time);
}
}
class Swimmer extends Athlete
{
Swimmer(String name)
{
setName(name);
}
@Override
public void compete()
{
int time = 100 + (int) (Math.random() * ((200d - 100d) + 1d));
setTime(time);
}
}
class Cyclist extends Athlete
{
Cyclist(String name)
{
setName(name);
}
@Override
public void compete()
{
int time = 500 + (int) (Math.random() * ((800d - 500d) + 1d));
setTime(time);
}
}
关于java - java接口(interface)与继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26319629/