Possible Duplicate:
force base class to use its own method and not overrided method
Suppose I have these 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();
OnlyOddInputsSquarer 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.
Edit: I can't modify Squarer
!