尝试深入挖掘OOP。
在这段设计的代码中,假设角色的声誉得分为1-5意味着“不是着名的”,否则如果超过10,则从下面的代码中, Warrior
实例的声誉默认为4,Swordman
为8:
package main;
public class BitOfAPuzzle {
public static void main(String[] args) {
Warrior conan = new Warrior("Conan");
Swordsman heman = new Swordsman("He-man");
conan.printReputation();
heman.printReputation();
}
}
class Warrior {
String name = "";
/* 0-5 => not yet famous; 6-10 is famous */
int reputation = 4;
Warrior(String name) {
this.name = name;
}
public void printReputation() {
if (this.reputation >=0 && this.reputation <= 5)
System.out.println(name + " needs to perform more deeds!");
else
System.out.println(name + " is already famous!");
}
}
class Swordsman extends Warrior{
int reputation = 8;
Swordsman(String name) {
super(name);
}
@Override
public void printReputation() {
super.printReputation();
}
}
正如所料,
conan.printReputation();
打印Conan needs to perform more deeds!
,但:
heman.printReputation();
还会打印He-man needs to perform more deeds!
,但它应该打印相反的内容。不应该让子类对象使用自己的阴影属性作为值,而不是引用超类&#39;阴影属性?是什么解释了这种行为?