Search code examples
javasubclasssuperclass

Superclass method obtain subclass variable


I have a superclass and a subclass. And in the superclass I try to get the variable from the subclass using a method. I have 2 subclasses and each subclasses have different values on this variable. How do I do this? This is how it looks like:

public class SuperClass{

protected int health;

public int getHealth()
{
    return health;
}

And then I have my Subclasses:

public class SubClass1 extends SuperClass{

private int health = 30;

public SubClass1() {
    super();
}
}

public class SubClass2 extends SuperClass{

private int health = 50;

public SubClass2() {
    super();
}
}

And then I try to test this using JTestUnit:

public class SubClass1{

@Test
public void testGetHealth()
{
    SubClass1 unit = new SubClass1();
    assertEquals(unit.getHealth(), 30);
}

But it doesn't work. How do I get the value depending if it's SubClass1 or SubClass2 object(instance?) that I am creating? Thanks in advance!


Solution

  • Remove

    private int health = 30;
    

    which declares a new variable whose name hides the variable in the super class.

    And initialize in the constructor(s)

    public SubClass2() {
        super();
        health = 30;
    }