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!
It seems to me that the class Squarer is not well designed. If you really need a dirty trick to make this work, you could also override the method
square():But… a square of a odd number is not even, so this should not really be a problem. I suppose this is just an example and your real problem is different.
Edit: OK, if this doesn’t work, there is even a dirtier method: in
setValuecheck the stack and if it was called fromsquarecallsuper.setValueinstead. I don’t recommend this, but If you really really need to get this done, check here to see how to do it.