0

I've got a question about overriding methods. OK, we've got an OOP here, I can understand what result I'll got. But.. How does the jdk resolve, what implementation to use in each case?

public class One {
    One() {
        run();
    }

    public void run() {
        System.out.println("One");
    }
}

public class Two extends One {
    @Override
    public void run() {
        System.out.println("Two");
    }
}

public class Test {
    public static void main(String[] args) {
       One test = new Two();
    }
}

I'm really sorry for not very good code listing, I was in a hurry. Changes added.

katsanva
  • 115
  • 1
  • 7

2 Answers2

2

First of all the way the classes have been declared is wrong and also static menthods do not take part in overriding, because static methods are not bound to objects.

0

Java is going to look up the function in the vtable for Two. If it's not found, it'll look in the vtable for One. In this case, it's found (and directly noted with @Override), so it's used.

https://stackoverflow.com/a/1543311/431415

Basically, it's going to go from most specific to least specific, looking for a function that matches.

Community
  • 1
  • 1
SubSevn
  • 1,008
  • 2
  • 10
  • 27
  • The answer from Theodoros is more complete than this one. – SubSevn May 17 '13 at 16:52
  • In fact, this is what I was looking for, thank you. Can you tell me more about vtables in Java or something? – katsanva May 17 '13 at 22:04
  • http://en.wikipedia.org/wiki/Dynamic_dispatch and http://stackoverflow.com/questions/6606481/virtual-table-dispatch-table The concept is similar between C++/Java, but in Java all your methods will be virtual unless declared with `final`. – SubSevn May 20 '13 at 10:50