简体   繁体   中英

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!

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;
}

You have to override method getHealth() for each sub class, ie

public class SuperClass{
    protected int health;

    public int getHealth() {
        return health;
    }
}


public class SubClass{
    private int health;

    public int getHealth() {
        return health;
    }
}

public class SubClass{
    public int getHealth() {
        return super.getHealth() * 2;
    }
}

Please pay attention that

  1. I renamed your classes that should start with capital letter by convention.
  2. Implementation of getHealth in first case uses its own variable while in second case calls getHealth() of super class and multiplies it by 2. This is just an usage example.

EDIT

Obviously this design is good for non-trivial implementations of methods, ie when method implement some logic. In your case you can just pass health through constructor:

public class SuperClass{
    protected int health;
    public SuperClass(int health) {
        this.health = health;
    }
    public int getHealth() {
        return health;
    }
}


public class SubClass1{
    public SuperClass1(int health) {
        super(health);
    }
}

public class SubClass2{
    public SuperClass2(int health) {
        super(health);
    }
}

But as far as the case is really simple, so there is not need to create sub classes at all, so you can just create your super class and create instances that hold different values of health:

SuperClass c1 = new SuperClass(1);
SuperClass c2 = new SuperClass(2);

如果您想要特定对象的健康值,则应该返回this.health。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM