简体   繁体   English

Java中的构造函数和抽象类

[英]constructors and abstract classes in java

I have an abstract class Entity.java and a class which extends this, Magician.java . 我有一个抽象类Entity.java和一个扩展了该类的类Magician.java Whenever I create a new Magician("Ged", 300) ; 每当我创建一个new Magician("Ged", 300) and then call System.out.println() it always prints null(0) , and I'm not sure why when it should print Ged(300). 然后调用System.out.println()总是打印null(0) ,我不确定为什么什么时候应该打印Ged(300)。 Here is the relevant code: 以下是相关代码:

Entity fields/ constructor: 实体字段/构造函数:

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;
    }

    ...

}

Magician fields/ Constructor/ toString: 魔术师字段/构造函数/ 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 + ")";
    }

}

Main class: 班:

public static void main(String[]args) {

    Magician m1=new Magician("Ged",300);
    System.out.println(m1.toString());
}

Thanks in advance. 提前致谢。

You are shadowing the super class Entity 's instance fields name and lifePoints in the sub class Magician . 您将在子类Magician中隐藏超类Entity的实例字段namelifePoints

And those by by default set to null and 0 respectively. 并且默认情况下,它们分别设置为null和0。 Remove those instance fields declaration from sub class Magician . 从子类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 + ")";
    }

}

You are not initializing 您尚未初始化

protected String name;
protected int lifePoints;

of your Magician class 您的魔术师课

public Magician(String name, int lifePoints) {
    super(name, lifePoints); // initializing fields of parent(Entity) not of child(Magician)
    // TODO Auto-generated constructor stub
}

Also, protected should be used in Parent class, not in the child. 另外,protected应该在Parent类中使用,而不是在子级中使用。 Please revisit the basics of Java. 请重新阅读Java的基础知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM