我无法为以下问题提出更好的解决方案。我应该在我的积极战士类中使用“公共战士战士”的可见性,它扩展了这个父抽象类。教授告诉我,公开可见性是关键,但我似乎无法弄清楚如何正确使用它。我需要返回这个战士的攻击级别,如果我测试“10”,我最终会得到我在构造函数中设置的默认“3”。我查看了其他继承帖子,但我现在似乎对为什么我尝试的方法不起作用感到更加困惑。我不允许将 Builder 更改为非静态类,因为测试不起作用。
public class AggressiveWarrior extends Warrior {
private int level;
private int attack;
private int defense;
private AggressiveWarrior(int level) {
this.level = level;
}
@Override
public int getLevel() {
return this.level;
}
@Override
public int getAttack() {
return this.attack;
}
@Override
public int getDefense() {
return this.defense;
}
public static class Builder extends Warrior.Builder{
private AggressiveWarrior aggressiveWarrior;
public Builder(int level) {
aggressiveWarrior = new AggressiveWarrior(level);
aggressiveWarrior.attack = 3;
aggressiveWarrior.defense = 2;
}
public Warrior.Builder attack(int attack) {
return this; // have tried return this.warrior.attack;
}
public Warrior.Builder defense(int defense){
return this;
}
public Warrior build(){
return aggressiveWarrior;
}
}
}
public abstract class Warrior {
public int level;
public int attack;
public int defense;
public abstract int getLevel();
public abstract int getAttack();
public abstract int getDefense();
public static abstract class Builder{
public Warrior warrior;
public Builder attack(int attack) {
warrior.attack = attack;
return this;
}
public Builder defense(int defense) {
warrior.defense = defense;
return this;
}
public Warrior build() {
validate(warrior);
return warrior;
}
public void validate(Warrior warrior) {
if (warrior.level <= 0 && warrior.attack > 0 && warrior.defense > 0) {
throw new IllegalStateException("Level must be greater than 0. ");
} else if (warrior.defense <= 0 && warrior.attack > 0 && warrior.level > 0) {
throw new IllegalStateException("Defense must be greater than 0. ");
} else if (warrior.attack <= 0 && warrior.defense > 0 && warrior.level > 0) {
throw new IllegalStateException("Attack must be greater than 0. ");
} else if (warrior.attack <= 0 && warrior.level <= 0 && warrior.defense > 0) {
throw new IllegalStateException("Level must be greater than 0. Attack must be greater than 0. ");
} else if (warrior.level <= 0 && warrior.defense <= 0 && warrior.attack > 0) {
throw new IllegalStateException("Level must be greater than 0. Defense must be greater than 0. ");
} else if (warrior.attack <= 0 && warrior.defense <= 0 && warrior.level > 0) {
throw new IllegalStateException("Attack must be greater than 0. Defense must be greater than 0. ");
}
else if (warrior.level <= 0 && warrior.defense <= 0 && warrior.attack <= 0) {
throw new IllegalStateException(
"Level must be greater than 0. Attack must be greater than 0. Defense must be greater than 0. ");
}
}
}
}