【发布时间】: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)而不是对象,并且我会使用相同的参数覆盖这些方法。