Reputation: 49
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!
Upvotes: 1
Views: 1419
Reputation: 115328
You have to override method getHealth()
for each sub class, i.e.
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
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, i.e. 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);
Upvotes: 1
Reputation: 397
You should be returning this.health if you want that specific object's value for health.
Upvotes: 0
Reputation: 109547
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;
}
Upvotes: 4