Override java methods without affecting parent behaviour

Posted by Timmmm on Stack Overflow See other posts from Stack Overflow or by Timmmm
Published on 2012-11-22T10:56:03Z Indexed on 2012/11/22 10:59 UTC
Read the original article Hit count: 193

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about oop