Java call base method from base constructor

How to call Super::printThree from Super::Super()?
In the example below I call Test::printThree instead.

class Super {
        Super() { 
        printThree(); // I want Super::printThree here!
        }
        void printThree() { System.out.println("three"); }
}
class Test extends Super {
        int three = 3
        public static void main(String[] args) {
                Test t = new Test();
                t.printThree();
        }
        void printThree() { System.out.println(three); }
}

output:
0    //Test::printThree from Super::Super()
3    //Test::printThree from t.printThree()

You can't - it's a method which has been overridden in the subclass; you can't force a non-virtual method call. If you want to call a method non-virtually, either make the method private or final.

In general it's a bad idea to call a non-final method within a constructor for precisely this reason - the subclass constructor body won't have been executed yet, so you're effectively calling a method in an environment which hasn't been fully initialized.


You're violating the whole idea behind dynamic dispatching and inheritance here. Just don't do it (and it's pretty hard to circumvent in java anyhow). Instead make the function private and/or final so that it can't be overwritten in the inherited class


If Super needs to ensure that printThree() isn't overridden, that method needs to be declared as final. Alternatively, the overriding method in Test can decide to call the overriden method if it chooses:

@Override
void printThree() { super.printThree(); }

If the base class doesn't mark a method as final, it's giving up the right not to have deriving classes override it and do as they please.