java中的构造函数和抽象类

时间:2014-04-25 11:13:09

标签: java constructor null abstract-class super

我有一个抽象类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());
}

提前致谢。

2 个答案:

答案 0 :(得分:3)

您正在影响子类Entity中的超类name的实例字段lifePointsMagician

默认设置为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的基础知识。