Parent instance = new Child();
instance.method();
When we call method, JVM will find child method directly or find parent class firstly, find child, find method, or some other sequence?
Parent instance = new Child();
instance.method();
When we call method, JVM will find child method directly or find parent class firstly, find child, find method, or some other sequence?
If I may add a more comprehensive example:
class Parent {
public void print() {
System.out.println("Hello from Parent");
}
}
class Child extends Parent {
@Override
public void print() {
System.out.println("Hello from Child");
}
}
public class Main {
public static void main(String[] args) {
Parent parent = new Child();
parent.print();
}
}
This program will print Hello from Child
. Although we instantiate the Child
via the Parent
, Java will look for the "nearest" implementation of print()
, starting from the child.