抽象类和方法出错

时间:2014-05-25 13:46:28

标签: java arrays methods abstract-class

我有一个抽象类玩家,我想创建两种玩家。快速和技术运动员。所以我创建了这个abtsract类:

public abstract class Player
{
    private int speed;
    private int technical;
    private Cell playerCell;

    public abstract void computeAbility();
    public abstract void clonePlayer();

    public Player(){
        Random rand = new Random();
        speed = rand.nextInt(50);
        technical = rand.nextInt(50);
    }

    //i also have accesor and mutator methods
}




  public class FastPlayer extends Player
{
    private int overallAtrributes;

    public FastPlayer(){
        super();
        setSpeed(2*getSpeed());
    }

    public void computeOverallAtrributes(){
                overallAtrributes = getSpeed() + getTechnical();
    }

    public void clonePlayer(){
        FastPlayer cloneFastPlayer = new FastPlayer();
        cloneFastPlayer.setTechnical(getTechnical());
        cloneFastPlayer.setSpeed(getSpeed());
    }
}



public class TechnicalPlayer extends Player
{
    private int overallAtrributes;

    public TechnicalPlayer(){
        setTechnical(2*getTechnical());
    }

    public void computeOverallAtrributes(){
        overallAtrributes = getSpeed() + getTechnical();
    }

    public void clonePlayer(){
        TechnicalPlayer cloneTechnicalPlayer = new TechnicalPlayer();
            cloneTechnicalPlayer.setTechnical(getTechnical());
            cloneTechnicalPlayer.setSpeed(getSpeed());
        }
}

现在我想在Player类中创建一个reproducePlayer方法来生成与当前播放器相同类型的播放器,并且我想将新人放在同一个Cell中。 所以我在Player类中创建了这个方法:

public void reproduce(){
        this.clonePlayer();
        //how can i put the new Player in the same Cell with current Player?
    }

我还想创建一个方法movePlayer,它将Player移动到我的数组的Random neighbor Cell中。我还没有创建Cell类。

2 个答案:

答案 0 :(得分:2)

你需要在公共类中进行克隆..而不是覆盖它或调用它。

类似的东西:

玩家:

public abstract Player clonePlayer();
protected Player clonePlayer(Player newPlayer){
    newPlayer.setTechnical(getTechnical());
    newPlayer.setSpeed(getSpeed());
    return newPlayer;
}

在玩家扩展课程下:

Class TechnicalPlayer extends Player
public Player clonePlayer() {
   return super.clonePlayer(new TechnicalPlayer ());
}

这应该是那样的..希望有所帮助     }

答案 1 :(得分:0)

因为所有的实现类都有no-args构造函数,所以你可以在抽象类上定义一个方法,它使用反射来创建与当前类相同的另一个类的实例:

public Player reproducePlayer() {
    Player p;
    try {
        p = getClass().newInstance();
    catch (InstantiationException | IllegalAccessException ignore) {}
    p.speed = speed;
    p.technical = technical;
    p.playerCell = playerCell;
    return p;
}