这是我写的两类代码..这里的问题是我不知道如何定义类字段来表示草,火和水作为使用静态的类型.. 另外我不确定我是否以正确的方式使用了超级函数..如何正确调用父的构造函数以便我不必重新定义“knockedOut boolean”并且能够使用Fire作为类型? 问题可能令人困惑,但我不确定如何更好地解释它:(对不起
public abstract class Pokemon {
private String name;
private String type;
private int attack;
private int health;
private boolean knockedOut;
static private String Grass;
static private String Water;
static private String Fire;
public Pokemon (String n, String t, int a, int h) {
name = n;//state
type = t;//state
attack = a;//state
health = h;//state
knockedOut = false;
}
public abstract int takeDamage(Pokemon enemy);
public String toString() {
return "}";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public boolean isKnockedOut() {
return knockedOut;
}
public void setKnockedOut(boolean knockedOut) {
this.knockedOut = knockedOut;
}
}
public abstract class Charizard extends Pokemon {
private static String Fire;
private int attackFire;
private int healthFire;
private static String Water;
private static String Grass;
public Charizard(int a, int h) {
super("Charizard", Fire, a, h);
attackFire = a;
healthFire = h;
}
public int takeDamage(Pokemon enemy){
int enemyAttack = enemy.getAttack();
if(enemy.getType().equals(Water)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()*2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
}
else if(enemy.getType().equals(Fire)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()*2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
}
else if(enemy.getType().equals(Grass)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()/2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
if(healthFire <=0){
Charizard.set = true;
}
}
return enemyAttack;
}
}
答案 0 :(得分:0)
您想要声明您的不同类型:
static public final String GRASS= "Grass";
static public final String WATER = "Water";
static public final String FIRE = "Fire";
(我在此遵循既定惯例,声明static
,public
和final
的字段应具有全部大写字母的名称。)
通过声明这些字段public
,可能需要测试Pokemon
类型的任何其他类(包括扩展Charizard
的类,例如Pokemon
)使用它们。通过声明它们final
,即使它们是public
,也没有人可以更改它们。通过为它们提供初始值,您可以使它们真正用于区分不同类型的Pokemon
,并避免在您第一次执行NullPointerException
时出现的不可避免的p.getType().equals(Pokemon.FIRE)
至于knockedOut
,看起来你正在以正确的方式处理它。字段knockedOut
在Pokemon
中是私有的,但您提供了其他类可以(并且确实)用来访问它的公共getter和setter方法。