Java – override constructor
I'm very confused about overriding constructors The constructor can't be overridden is the result I got when I searched it in Google. My problem 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 get the result
In Super constructor In Sub.test() In Sub constructor In Sub.test()
Notice that the test method in the subclass has been executed Whether to show whether the super constructor is overridden Is it correct?
Solution
Constructors are not polymorphic - you won't overwrite them at all You create new constructors in subclasses, and each subclass constructor must be linked (possibly indirectly) to a superclass constructor If there is no explicit link to the constructor, an implicit call to the parameterless superclass constructor is inserted at the beginning of the subclass constructor body
Now in terms of overriding methods - an object is the "final type" from the beginning, including when executing a superclass constructor Therefore, if you print getClass () in the super constructor code, you will still see sub. in the output. The result is that the rewriting method (i.e. sub.test) is called, even if the sub constructor has not been executed
This is basically a bad idea. You should almost always avoid calling the method that might be overwritten in the constructor - or record it very clearly (so the subclass code realizes it can't rely on the existing variables) and initialize appropriately.