Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call own, non-overridden method

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading