No, constructor overriding is not possible in Java, so whether it is runtime polymorphism or not is out of question.
If you override a method of parent class in subclass and try to call that method using parent class reference variable, JVM decides which method to call at runtime. However, each class will have their own copy of constructors.
For example, A super class can have an empty arg constructor and subclass can also have an empty arg constructor. When you instantiate a subclass, it not only execute subclass constructor but also calls super class constructor, in fact, superclass constructor gets executed first and then subclass constructor.
So, when you are instantiating an object, you are explicitly calling the constructor, by yourself, JVM doesn’t decide at runtime which constructor is to be called.
Let us look at an example:
package com.techstackjournal;
class Alpha {
public Alpha() {
System.out.println("Alpha Constructor");
}
}
class Beta extends Alpha {
public Beta() {
System.out.println("Beta Constructor");
}
}
public class Main {
public static void main(String[] args) {
Alpha alpha = new Beta();
}
}
Output:
Alpha Constructor
Beta Constructor
- In the above example, we have a super class Alpha with a no-arg constructor and subclass Beta with a no-arg constructor
- But it doesn’t mean that subclass is overriding the superclass constructor
- If subclass overrides the superclass constructor it should only execute Beta constructor
- But it doesn’t happen like that, JVM executes both superclass and subclass constructors, Alpha constructor first and then Beta constructor
- With this we can clearly say that writing same argument constructor in subclass neither called constructor overriding nor it will be a runtime polymorphism