Question

I have an abstract class Entity.java and a class which extends this, Magician.java. Whenever I create a 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). 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:

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.

Was it helpful?

Solution 2

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. Please revisit the basics of Java.

OTHER TIPS

You are shadowing the super class Entity's instance fields name and lifePoints in the sub class Magician.

And those by by default set to null and 0 respectively. Remove those instance fields declaration from sub class 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 + ")";
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top