0
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?

cow12331
  • 245
  • 2
  • 3
  • 9
  • possible duplicate of [When do you use Java's @Override annotation and why?](http://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why) – Shantha Kumara Jan 16 '15 at 04:12
  • @ShanthaKumara It seems no answers. Could you just tell me whether the JVM will find the method in subclass directly depend on the actual implemented class? – cow12331 Jan 16 '15 at 04:23
  • The `method()` is first searched in the Child then Parent. In other words, JVM starts from most specific implementation to generic implementation to find the `method()`. – Shantha Kumara Jan 16 '15 at 04:54

1 Answers1

0

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.

tdranv
  • 1,140
  • 11
  • 38