我正在创建一个战斗模拟游戏。我有一个攻击职业和一个战士职业。
public class Attack {
private String name;
private int points;
public Attack(String name, int points) {
this.name= name;
this.points =points;
}
//getters
public String getName() {
return name;
}
public int getPoints() {
return points;
}
public String toString() {
return ("Name of the attack = " + name + " damage = " + points) ;
}
}
由于战士有不同的攻击,我不能使用静态,因为它会覆盖之前的攻击。 Monster 类片段:
public Attack[] getAttacks() {
return attacks;
}
public void attack(String attackname, Warrior otherWarrior){
// How would I access the attack from the class?
}
我如何才能访问攻击字段? 谢谢。
最佳答案
正如您可以访问 this
Monster
类的实例方法一样,您也可以访问 Warrior
类的实例方法:
public class Monster {
Attack[] attacks;
// ...
public Attack[] getAttacks(){
return attacks;
}
public void attack(String attackname, Warrior otherWarrior){
Attack[] monsterAttacks = this.getAttacks();
// Assuming Warrior has the method `getAttacks()`
Attack[] warriorAttacks = otherWarrior.getAttacks();
// ...
}
}
public class Warrior {
Attack[] attacks;
// ...
public Attack[] getAttacks() {
return attacks;
}
}
关于java - 如何在没有静态的情况下访问不同类中的字段? (JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58525451/