0

I have a subclass that needs to inherit a method and a variable, and I want to be able to make several instances of the subclass. However, I can't change health's value from the class Glob.

Here is my code:

public class Monster
{
int health;

    public int getHealth()
    {
        return health;
    }
}

class Glob extends Monster
{
    health = 6; //  <- Error
}
  • You have not specific what is the problem. The code you posted seems valid, but where is the code where you're *trying to make it work*? – mjuarez Mar 07 '15 at 04:53

1 Answers1

1

You cannot just shadow variable of superclass like that. You can do it in constructor though -

class Glob extends Monster
{
    public Glob() {
        health = 6;
    }
}
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289