如何解决如何在类上使用具有不同参数的抽象方法?
如何在两个类上使用具有覆盖的抽象方法。?但是这两个类具有相同的方法但具有不同的参数。是否有任何解决方案,或者我应该使方法不抽象,并且每个类的类型都不同?
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 泛型。这是一个例子:
字符类
public abstract class Charachter<T> {
public abstract int attack(T object);
}
您声明类 Character
使用 T
类型的参数进行参数化。
怪物类
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
。
如果基方法有一个 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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。