【问题标题】:Is it possible to put this method in the parent class instead?是否可以将此方法放在父类中?
【发布时间】:2018-02-24 03:08:26
【问题描述】:

我有一个方法 sleep(),它将实例的 int hp 设置为 final int MAX_HP。我把这个方法放在了 Warrior 和 Mage 类中,它们是 Character 的子类。这里的问题是我在每个子类中单独定义 MAX_HP,因为战士和法师会有不同的 Max_HP,所以似乎我还必须在每个类中声明 sleep() 而不是在父类中只声明一次 - 效率低下。有没有办法可以在父类中声明睡眠方法并以某种方式从子类中检索 MAX_HP?或者有更好的方法吗?

//Warrior Class
public class Warrior extends Adventurer{
    private final int MAX_HP = 150;
    public void sleep(){
    setHp(MAX_HP);
    System.out.println(getName() + "fully restored HP!");
 }
}

//Mage Class
public class Mage extends Adventurer{
    private final int MAX_HP = 100;
    public void sleep(){
    setHp(MAX_HP);
    System.out.println(getName() + "fully restored HP!");
 }
}

//Adventurer Class
public abstract class Adventurer{
private int hp;
public Adventurer(int hp){
    this.hp = hp;
 }
public int getHp(){
    return this.hp;
 }
public void setHp(int hp){
    this.hp = hp;
 }

【问题讨论】:

    标签: java return arguments polymorphism parent-child


    【解决方案1】:

    是的,你可以。

    在抽象类Adventurer里面添加一个抽象方法:

    public abstract int getChildHP();
    

    并让WarriorMage 实现它:

    public int getChildHP() { return MAX_HP };
    

    MAX_HP 当然每个人都不同)。

    sleep() 方法(从子类中删除)移动到抽象类并实现它:

    public void sleep() {
        setHp(getChildHP());
        System.out.println(getName() + "fully restored HP!");
    }
    

    调用该方法时,会根据实例调用相关的getChildHP()。 现在sleep() 在父级 1234562 中只存在一次 ==> 没有代码重复。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2010-11-01
      • 2023-03-08
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2010-12-24
      • 2012-07-12
      相关资源
      最近更新 更多