blgrnboy
blgrnboy

Reputation: 5167

Java - Return field value of class that extends the super class

When I create an instance of "Sword", and calls the getName(), I receive null. How can I make it so that getName() in Weapon class returns whatever "name" is set to in Weapon.

public abstract class Weapon extends items.Item {

    public String name;

    public int damage;

    public ItemType itemType = ItemType.Weapon;

    public String getName(){
        return name;
    }

}

public class Sword extends Weapon{

    int damage = 10;
    int manaCost = 0;
    String name = "Steel Sword";
}

Upvotes: 0

Views: 123

Answers (2)

kmecpp
kmecpp

Reputation: 2489

You can add a constructor to your Weapon class so that all of its subclasses must use it to initialize the correct data for that class

public abstract class Weapon {

    public String name;
    public int damage;
    public ItemType itemType = ItemType.Weapon;

    public Weapon(String name, int damage) {//Constructor for creating a weapon to be used by subclasses
        this.name = name;
        this.damage = damage;
    }
}

And then to create a Sword with the name "Sword" and damage of 10 you would just invoke its superclasses constructor like this:

public class Sword extends Weapon {

    public Sword() {
        super("Sword", 10); //Calls the constructor from the Weapon class with the values "Sword" and 10
    }
}

I would think this is the much preferred solution, because it will cause compile time warnings if Sword does not call the constructor for a weapon, and it will ensure that all the fields are initialized correctly.

Upvotes: 1

rgettman
rgettman

Reputation: 178293

Your name variable in Sword is different than the one in Weapon -- it hides the one in Sword. When you have a variable of type Weapon, accessing name will access Weapon's name, which is uninitialized, so it remains null.

Instead of declaring a new variable, you can create a constructor in Sword that sets the existing name variable to what you want.

Upvotes: 3

Related Questions