I need to create new warrior, assign name, and get his description with function specified in GameCahracter class. When I am trying to run – it stops on weapon.type ; // <<Exception showing that weapon=null. Why? As far as I know warrior constructor assigned to variable weapon a link to new Weapon.Sword. Then using variable weapon I should be able to access it’s field type. What is wrong here?
abstract class GameCahracter{
public String name;
public String type;
public Weapon weapon;
public int hitPoints;
public String getDescription(){
return name + "; " +
type + "; " +
hitPoints + " hp; " +
weapon.type ; // << Exception
}
public static class Warrior extends Player{
public Warrior() {
type = "Warrior";
hitPoints = 100;
Weapon.Sword weapon = new Weapon.Sword();
}
}
abstract class Player extends GameCahracter {
}
abstract class Weapon {
public int damage;
public String type = "default";
public int getDamage(){
return this.damage;
}
public static class Sword extends Weapon{
public Sword() {
String type = "Sword";
int damage = 10;
}
}
}
GameCahracter.Warrior wr = new GameCahracter.Warrior();
wr.setName("Joe");
System.out.println( wr.getDescription());
EDIT1
For some reason I’m having default string when printing out weapon.type. Why? How can I get typeto be Sword?
In this moment your constructor leave
weaponfield tonull. Simply creates aSwordinstance that is garbaged once is out of the scope.So change the line
in your
Warriorconstructor withor better with
and you do a similar error in
Swordconstructor when you writechange them with