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
Don’t re-declare the member variables. Instead you should set the values inside the constructor.
Another option would be to create a
GameCahracterconstructor that takes arguments that match each of the member variables.As a side note: public member variables are a bad idea.