如何在 类 上使用具有不同参数的抽象方法?

How can I use abstract method with different parameters on classes?

如何在两个 classes 上使用带覆盖的抽象方法。?但是这两个classes的方法相同,参数不同。是否有任何解决方案,或者我应该使方法不抽象并为每个 class 键入不同的方法?

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;
}

您正在寻找 Java 仿制药。这是一个例子:

字符class

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

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

怪物class

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

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

英雄class

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

您声明您的 Hero class 扩展了类型 Monster 的基础 class,因此您重写的方法的类型将为 Monster .

如果基方法有一个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
}