[英]Can I have access to a field of a child object from inside a method which is not overridden by the child class?
[英]Is there a way to implement a method on a child class that I can access the attributes from it's child?
我正在嘗試構建一個學習Java的應用,基本上這是在控制台上進行的足球比賽。
班級球員具有姓名,號碼,年齡等所有屬性。還有其他一些從球員擴展的類別,即球員角色(前鋒,后衛,中場,守門員)。 角色實現了一個接口,該接口具有獲取每個屬性的方法(如防御力和攻擊力)。 因此,這里有一種方法,即“通用權力”,該公式等於每個人,獨立於玩家的角色。
如果在子類的類方法中設置“通用權限”,則必須在每個角色類中編寫相同的代碼幾次(我幾乎可以肯定這是錯誤的。代碼重用)。
也許我必須在接口上實現該方法,但是我不知道如何進行。
我在GitHub上有一個鏈接-在Develop分支上。
下面是一些代碼,這些代碼試圖了解我要弄清楚的內容。
public interface PlayerAttributes {
PlayerPosition getPlayerPosition(PlayerPosition position);
Double getAttackPower(Float value);
}
class Player {
String name;
Integer number;
PlayerPosition position; //Enum
}
public class Defender extends Player implements PlayerAttributes {
@Override
public PlayerPosition getPlayerPosition(PlayerPosition position) {
return PlayerPosition.DEFENDER;
}
@Override
public Double getAttackPower(Float value) {
return value * 1.2;
}
@Override
public Double getDefensePower(Float value) {
return value * 2.5;
}
}
以下答案僅是一個建議,並不是迄今為止唯一的解決方案。 它通過讓Player
實現PlayerAttribute
接口來使用抽象類:
public interface PlayerAttributes {
PlayerPosition getPlayerPosition(PlayerPosition position);
Float getAttackPower(Float value);
Float getDefensePower(Float value);
}
abstract class Player implements PlayerAttributes {
String name;
Integer number;
@Override
public PlayerPosition getPlayerPosition(PlayerPosition position) {
return PlayerPosition.DEFENDER;
}
@Override
public Float getAttackPower(Float value) {
return value * attackPowerMultiplier();
}
public Float getDefensePower(Float value) {
return value * defensePowerMultiplier();
}
public abstract Float attackPowerMultiplier();
public abstract Float defensePowerMultiplier();
}
class Defender extends Player implements PlayerAttributes {
public static final Float ATTACK_POWER_MUTLIPLIER = 1.2f;
public static final Float DEFENSE_POWER_MUTLIPLIER = 2.5f;
@Override public Float attackPowerMultiplier() {
return ATTACK_POWER_MUTLIPLIER;
}
@Override public Float defensePowerMultiplier() {
return DEFENSE_POWER_MUTLIPLIER;
}
}
enum PlayerPosition {
DEFENDER
}
get<Type>PowerMultiplier()
方法仍將非常相似,但是這種方法試圖使重復最小化。
關於您的代碼的兩個說明:
float
,則它應該返回一個float
(與double
相同),除非明確地表明有必要或打算進行轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.