簡體   English   中英

如何正確更改父子 object 中存在的字段的值

[英]How to properly change value of a field that exist in parent and child object

所以我有一個父 class 戰士和一個擴展戰士的騎士 class。 任務說明中說勇士有 2 個字段:

  • int健康= 50,
  • 智力攻擊 = 5

Knight 的攻擊量必須為 7。如何在不破壞 SOLID 規則等的情況下正確更改 Knight“攻擊”字段。我的代碼看起來像那個 rn。

public class Warrior {

    private int health;
    private int attack;

    public Warrior() {
        this.health = 50;
        this.attack = 5;
    }

    public void setAttack(int attack) {
        this.attack = attack;
    }

-----------------------------------------------

    public class Knight extends Warrior {

    public Knight() {
        super.setAttack(7);
      }
    }

它可以按我的意願工作,但我認為我找不到更好的解決方案。 我可以只更改公共攻擊場的修改器,然后更改 go 的 super.attack 嗎?

您可以為Warrior class 創建一個無參數構造函數,該構造函數使用this(50, 5)調用重載構造函數。 然后,您可以在Knight的 Child class 中使用super(50, 7)來調用相同的構造函數,但具有不同的值。

如果您真的不想在創建Knight時傳遞騎士的生命值,您還可以添加一個僅用於攻擊的重載選項作為super(7)之類的參數:

public class Warrior {

    private int health;
    private int attack;

    public Warrior() {
        this(50, 5);
    }
    
    public Warrior(int health, int attack) {
        this.health = health;
        this.attack = attack;
    }

    public void setAttack(int attack) {
        this.attack = attack;
    }
}

//Separate Java File
public class Knight extends Warrior {
    public Knight() {
        super(50, 7);
    }
}

如果您需要在創建 object之后更改值,我會使用setAttack之類的東西。

當您需要多個具有相同行為和屬性集的對象時,無需為每個對象創建單獨的class

您可以根據需要創建任意數量的實例,只有一個class

如果您希望這些對象具有一組固定的屬性(或僅修復部分屬性,以及在實例化 class 時提供的其他屬性),您可以創建一個enum ,該常量將代表您需要的所有類型的 object WARRIORKNIGHT

每個枚舉常量都可以維護一組固定的屬性,這些屬性對應於 object 的特定風格之一。

例如:

public enum FighterType {
    WARRIOR(5), KNIGHT(7);
    
    private int attack; // add other properties, like health if needed

    FighterType(int attack) {
        this.attack = attack;
    }

    // getters
}

你的單基地 class 可能看起來像:

public class Fighter {
    private String name;        // provided in the client code while creating a new instance
    private int health = 50;    // if you want this property to be the same for every instance, there's no need to assign it inside the constructor
    private int attack;         // comes with the type
    private FighterType type;   // WARRIOR, KNIGHT, etc.

    public Fighter(FighterType type, String name) {
        this.name = name;
        this.type = type;
        this.attack = type.getAttack();
    }

    // getters, etc.
}

使用示例:

Fighter richard = new Fighter(FighterType.KNIGHT, "Richard The Lionhearted");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM