Search code examples
javapolymorphismoverriding

How to Ignore Overriding


Code first - question later


class A {
    int value() { return 1; }   //The value

    int getThisValue() { return this.value(); }  //gives back the overridden value
    int getValue() { return value(); }           //this too

    int getSuperValue() { return value(); }     //for overriding in B
    final int getSuperValue2() { return getSuperValue(); }  
    //Here I get the not-overridden value
    //TODO: simplify the process of getting the un-overridden value

}

class B extends A {
    @Override
    final int getSuperValue() { return super.value(); }  //returns the correct value
}

public class Test extends B{
    @Override
    int value() { return 3; }    //overriding the value

    public static void main(String[] args) {  //output
        Test test = new Test();

        System.out.println("getValue(): " + test.getValue());                 //3
        System.out.println("getThisValue(): " + test.getThisValue());         //3
        System.out.println("getSuperValue(): " + test.getSuperValue());       //1
        System.out.println("getSuperValue2(): " + test.getSuperValue2());     //1
    }
}

I have A class, in which I access value.
This value gets overridden
-> I want to access the un-overrridden value in A
My Question: Is getSuperValue2() the only way get the un-overridden value or is there another way?

I want to know if I can protect my Code, by only accessing Code I know, but making my code overrideable for those, that want to change the functionality a bit


Solution

  • There is indeed no way once a subclass starts overriding. That's by design - you don't get to refer to "The implementation of the getValue() method the way class A does it", that's the wrong mental model. You merely get to refer to the notion of "the implementation of the getValue() method the way this object does it" (note the difference: Think 'objects', not 'classes'). Once we talk solely about 'the impl from this object', then the idea of "But I want the unoverridden value" no longer makes any sense, hence why you can't do it.

    want to know if I can protect my Code

    Yeah of course. Just mark the method final! This is a sometimes-observed pattern:

    public class Parent {
       public final void init() {
         childInit();
         doStuffThatChildClassesCannotStopFromHappening();
       }
    
       protected void childInit() {
         // does nothing - child classes can override if they wish
       }
    }