我有一个抽象类Entity.java
和一个扩展它的类,Magician.java
。每当我创建一个new Magician("Ged", 300)
;然后调用System.out.println()
它总是打印null(0)
,我不知道为什么它应该打印Ged(300)。以下是相关代码:
实体字段/构造函数:
public abstract class Entity {
protected String name;
protected int lifePoints = 0;
public Entity(String name, int lifePoints) {
assert (lifePoints >= 0);
this.name = name;
this.lifePoints = lifePoints;
}
...
}
魔术师字段/构造函数/ toString:
public class Magician extends Entity implements SpellCaster {
public Magician(String name, int lifePoints) {
super(name, lifePoints);
// TODO Auto-generated constructor stub
}
protected String name;
protected int lifePoints;
...
public String toString() {
return name + "(" + lifePoints + ")";
}
}
主要类:
public static void main(String[]args) {
Magician m1=new Magician("Ged",300);
System.out.println(m1.toString());
}
提前致谢。
答案 0 :(得分:3)
您正在影响子类Entity
中的超类name
的实例字段lifePoints
和Magician
。
默认设置为null
和0。从子类Magician
中删除那些实例字段声明。
public class Magician extends Entity implements SpellCaster {
public Magician(String name, int lifePoints) {
super(name, lifePoints);
// TODO Auto-generated constructor stub
}
...
public String toString(){
return name + "(" + lifePoints + ")";
}
}
答案 1 :(得分:1)
您没有初始化
protected String name;
protected int lifePoints;
你的魔术师课程
public Magician(String name, int lifePoints) {
super(name, lifePoints); // initializing fields of parent(Entity) not of child(Magician)
// TODO Auto-generated constructor stub
}
此外,protected应该在Parent类中使用,而不是在子级中使用。请重新阅读Java的基础知识。