【问题标题】:How can I use abstract method with different parameters on classes?如何在类上使用具有不同参数的抽象方法?
【发布时间】:2021-06-18 08:19:42
【问题描述】:

如何在两个类上使用具有覆盖的抽象方法。?但这两个类的方法相同,但参数不同。是否有任何解决方案,或者我应该使方法不是抽象的,并且每个类的类型都不同?

public abstract int attack(Object object); // here is my abstract method from Character class



public int attack(Hero hero){ // this method from monster class
    int currentHeroHealth;
    int reducedDamage;
    System.out.println("You have been attacked by monster!");
    int attackDamage = getAttackDamage();
    int attackSpeed = getAttackSpeed();
    int attack = attackDamage * attackSpeed;

    if(attack<hero.getArmor()){
        reducedDamage=hero.getArmor()-attack;

    }
    else{
        reducedDamage=attack-hero.getArmor();

    }
    currentHeroHealth=hero.getHealthPoints()-reducedDamage;
    hero.setHealthPoints(currentHeroHealth);
    return currentHeroHealth;

}




public int attack(Monster monster) { // this method from hero class
    System.out.println("You attacked to monster!");


    int currentMonsterHealth=monster.getHealthPoints()-HitPoints;
    if(currentMonsterHealth==0){
        System.out.println("You defeated the monster"+monster.getName());
        monster.setHealthPoints(0);
    }
    else {
        monster.setHealthPoints(currentMonsterHealth);

    }
    return currentMonsterHealth;
}

【问题讨论】:

  • 我认为你想多了。我会将 Character 类的攻击修改为 attack(Character character) 而不是对象,并且我会使用相同的参数覆盖这些方法。

标签: java oop methods abstract


【解决方案1】:

您正在寻找 Java 泛型。这是一个例子:

字符类

public abstract class Charachter<T> {
    public abstract int attack(T object);
}

您声明要使用 T 类型的参数对类 Character 进行参数化。

怪物类

public class Monster extends Character<Hero> {
    @Override
    public int attack(Hero object) {
        //your implementation
    }
}

您声明您的Monster 类扩展了具有Hero 类型的基类,因此参数将为Hero

英雄职业

public class Hero extends Character<Monster> {
    @Override
    public int attack(Monster object) {
        //your implementation
    }
}

您声明您的Hero 类扩展了具有Monster 类型的基类,因此您的覆盖方法的类型将为Monster

【讨论】:

    【解决方案2】:

    如果基方法有Object 参数,被覆盖的方法也需要有Object 参数。虽然子类可以使用更通用的参数覆盖方法,但不允许使用更专业的参数。

    但是,您可以使用instanceof 来决定调用什么方法:

    public int attack(Object object){
        if(object instanceof Hero){
            return attack((Hero)object);
        }
        if(object instanceof Monster){
            return attack((Monster)object);
        }
        //Do whatever you want to do if the object is neither a hero nor a monster
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-30
      • 2017-08-04
      • 1970-01-01
      • 2011-06-04
      • 2016-06-30
      • 1970-01-01
      • 2018-05-16
      相关资源
      最近更新 更多