J.Olufsen
J.Olufsen

Reputation: 13915

Cannot get fields of child nested class who have abstract parent

When trying to get field values of child nested static class, getting null. *1 *Each class file divided by horizontal line. How to retrieve the values of child Warrior?


abstract class GameCahracter{

        public String name;

    public String type;

    public Weapon weapon; 

    public int hitPoints;

    public String getDescription(){

        return type + "; " + name + "; " + hitPoints + " hp; " + weapon.type; 
    }

    public static class Warrior extends Player{

        public final String type = "Warrior";

        public int hitPoints = 100;

        public static final  Weapon.Sword weapon = new Weapon.Sword(); 

    }
}

abstract class Player extends GameCahracter {

}

GameCahracter.Warrior wr = new GameCahracter.Warrior();

wr.name = "Joe";

System.out.println( wr.getDescription());

OUTPUT:

null; Joe; 0 hp; null

Upvotes: 0

Views: 241

Answers (2)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13525

GameCahracter.name and GameCahracter.hitPoints were not assigned, so they remain null. Warrior.name and WarriorhitPoints.hitPoints were assigned, but they are different fields. It is a bad idea to have fields with the same name in parent and child (unlike methods).

Upvotes: 1

unholysampler
unholysampler

Reputation: 17321

Don't re-declare the member variables. Instead you should set the values inside the constructor.

public static class Warrior extends Player{
    public Warrior() {
      type = "Warrior";
      hitPoints = 100;
      weapon = new Weapon.Sword(); 
    }
}

Another option would be to create a GameCahracter constructor that takes arguments that match each of the member variables.

As a side note: public member variables are a bad idea.

Upvotes: 3

Related Questions