I am greatly confused with Overriding Constructors. Constructor can not be overridden is the result what i get when i searched it in google my question is
public class constructorOverridden {
public static void main(String args[]) {
Sub sub = new Sub();
sub.test();
}
}
class Super {
Super() {
System.out.println("In Super constructor");
test();
}
void test() {
System.out.println("In Super.test()");
}
}
class Sub extends Super {
Sub() {
System.out.println("In Sub constructor");
}
void test() { // overrides test() in Super
System.out.println("In Sub.test()");
}
}
when i run this i got the result as
In Super constructor
In Sub.test()
In Sub constructor
In Sub.test()
pls note the test method in subclass is executed. Is it shows that Superclass constructor is overridden. Whether is it correct ?
Constructors aren’t polymorphic – you don’t override them at all. You create new constructors in the subclass, and each subclass constructor must chain (possibly indirectly) to a superclass constructor. If you don’t explicitly chain to a constructor, an implicit call to the parameterless superclass constructor is inserted at the start of the subclass constructor body.
Now in terms of overriding methods – an object is of its “final type” right from the start, including when executing a superclass constructor. So if you print
getClass()in theSuperconstructor code, you’ll still seeSubin the output. The upshot of that is the overridden method (i.e.Sub.test) is called, even though theSubconstructor hasn’t yet executed.This is fundamentally a bad idea, and you should almost always avoid calling potentially-overridden methods in constructors – or document very clearly that it’s going to be the case (so that the subclass code is aware that it can’t rely on variables having been initialized appropriately etc).