[英]Error with abstract class and methods
我有一個抽象類的播放器,我想創建兩種播放器。 快速和技術玩家。因此,我創建了此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方法,以產生與當前Player相同類型的Player,並且我想將新人物放置在同一Cell中。 所以我在Player類中創建了這個方法:
public void reproduce(){
this.clonePlayer();
//how can i put the new Player in the same Cell with current Player?
}
我還想創建一個方法movePlayer,將Player移到我數組的隨機相鄰單元格中。 我還沒有創建Cell類。
您需要在公共類中創建克隆。然后重寫或調用它。
像這樣:
在球員下:
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 ());
}
應該是這樣的。希望對您有所幫助
因為所有實現類都具有無參數構造函數,所以您可以在抽象類上僅定義一個方法,該方法使用反射來創建與當前類相同的另一個實例:
public Player reproducePlayer() {
Player p;
try {
p = getClass().newInstance();
catch (InstantiationException | IllegalAccessException ignore) {}
p.speed = speed;
p.technical = technical;
p.playerCell = playerCell;
return p;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.