Please consider the following code.
class Base{
Base() {
print();
}
void print() {
System.out.println("Base");
}
}
class Child extends Base{
int i = 4;
public static void main(String[] args){
Base base = new Child();
base.print();
}
void print() {
System.out.println(i);
}
}
The program will print 0,4.
What I understand by this is, the method to be executed will be selected depending on the class of the actual object so in this case is Child
. So when Base
's constructor is called print method of Child
is called so this will print 0,4.
Please tell if I understood this correctly?
If yes, I have one more question, while Base class constructor is running how come JVM can call Child
's method since Child
's object is not created?
Runtime polymorphism can be achieved only through a pointer (or reference) of base class type.
Method overriding is an example of runtime polymorphism. In method overriding, a subclass overrides a method with the same signature as that of in its superclass. During compile time, the check is made on the reference type.
The primary advantage of runtime polymorphism is enabling the class to offer its specification to another inherited method. This implementation transfer from one method to another can be done without altering or changing the codes of the parent class object.
The runtime polymorphism can be achieved by method overriding. Java virtual machine determines the proper method to call at the runtime, not at the compile time. It is also called dynamic or late binding. Method overriding says the child class has the same method as declared in the parent class.
[...] the method to be executed will be selected depending on the class of the actual object
Yes, your understanding is correct: the method is selected based on the type of the object being created, so the call is sent to Child.print()
rather than Base.print()
.
while
Base
class constructor is running how come JVM can callChild
's method sinceChild
's object is not created?
When Base
's constructor is running, Child
object is already created. However, it is not fully initialized. That is precisely the reason to avoid making calls to methods that can have overrides from inside a constructor: the language allows it, but programmers should take extreme care when doing it.
See this Q&A for more information on problems that may happen when base class constructors call overridable methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With