Override java methods without affecting parent behaviour
- by Timmmm
suppose I have this classes (sorry it's kind of hard to think of a simple example here; I don't want any "why would you want to do that?" answers!):
class Squarer
{
public void setValue(int v)
{
mV = v;
}
public int getValue()
{
return mV;
}
private int mV;
public void square()
{
setValue(getValue() * getValue());
}
}
class OnlyOddInputsSquarer extends Squarer
{
@Override
public void setValue(int v)
{
if (v % 2 == 0)
{
print("Sorry, this class only lets you square odd numbers!")
return;
}
super.setValue(v);
}
}
auto s = new OnlyOddInputsSquarer();
s.setValue(3);
s.square();
This won't work. When Squarer.square() calls setValue(), it will go to OnlyOddInputsSquarer.setValue() which will reject all its values (since all squares are even). Is there any way I can override setValue() so that all the functions in Squarer still use the method defined there?
PS: Sorry, java doesn't have an auto keyword you haven't heard about! Wishful thinking on my part.