Home > OS >  Call own, non-overridden method
Call own, non-overridden method

Time:06-07

Say I have this code (not actually my code, but easier to understand):

public class A {
    private int i1, i2;

    protected int getSum() {
        return i1   i2;
    }

    protected int getSumTimes10() {
        return getSum() * 10;
    }
}

public class B extends A {

    protected int getSum() {
        throw new UnsupportedOperationException();
    }
}

public class C extends B {

    public void doSomething() {
        // cannot call getSum();
        System.out.println(getSumTimes10());
    }
}

I overrive getSum() in B so that any class that extends B cannot call it. However, I do need it in B itself.

Calling doSomething() on any C will cause an UnsupportedOperationException.

How can I make A use its own getSum() and not the overridden one so that I don't have to write the method twice?

CodePudding user response:

The language itself doesn't give you any specific tools to be able to do that. While there exists super.someMethod() to invoke a parent's implementation, there is no equivalent way to invoke a method which has the semantics that you're describing.

In the rare cases I've seen this be a desirable design choice, the usual workaround is to introduce a new method, possibly with some arbitrary prefix to make the name distinct, like do.

public class A {
    private int i1, i2;

    protected int getSum() {
        return doGetSum(); // delegate to non-overrideable version
    }

    protected int getSumTimes10() {
        return doGetSum() * 10; // delegate to non-overrideable version
    }
    
    private int doGetSum() {
        return i1   i2;
    }
}

Your base class can rely on the do___ version in cases where the overridden version would be undesirable and you never have to duplicate the implementation.

  • Related