Search code examples
javagetter-setterencapsulation

How to set text from encapsulated variable


I have placed this code in a new class

public class Monster {
private String name;
private int health, mana, attack;

public void setName(String name) {this.name=name;}
public void setHealth(int health) {this.health=health;}
public void setMana(int mana){this.mana=mana;}
public void setAttack(int attack){this.attack=attack;}

public String getName() {return name;}
public int getHealth() {return health;}
public int getMana() {return mana;}
public int getAttack(){return attack;}

public Monster(String name, int health, int mana, int attack) {
}

and want to use it in a different activity. I made sure to import the class in the activity and have written these codes:

Monster vampire = new Monster("Vampire", 2000, 300, 25);

I want to set text view according to what is written so I wrote:

    monsterName.setText(String.valueOf(vampire.getName()));
monsterHP.setText(String.valueOf(vampire.getHealth()));
monsterMP.setText(String.valueOf(vampire.getMana()));

but when I run the application, text view writes 'null' and monsterHP and monsterMP writes '0'. How do I set the text according to the class?


Solution

  • Custom constructor is not properly initialized. When call Monster vampire = new Monster("Vampire", 2000, 300, 25); no values are set, so obvious null:string and 0:numbers returns (java default initializers).

    Adapt with:

    public Monster(String name, int health, int mana, int attack) {
    this.name = name;
    this.health = health;
    this.mana = mana;
    this.attack = atack;
    }