-2
public class Main {
    static void method(A a){
        System.out.print("one");
    }

    static void method(B b){
        System.out.print("two");
    }

    static void method(Object obj){
        System.out.print("three");
    }

    public static void main(String[] args) {
        C c = new C(); 

        method(c);
    }
}
class A {}
class B extends A{}
class C extends B{}

As you see the title, i think it displays "three" but true answer is "two". Anyone can explain me? Thankss!

Victor
  • 3,841
  • 2
  • 37
  • 63
Emre KÖK
  • 3
  • 2
  • Why not run and [debug](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) it for yourself? – Turing85 Dec 14 '19 at 15:21
  • 1
    Overloading will resolve to the most specific type that applies to the argument. The most specific type that applies to a reference of type C is B. – khelwood Dec 14 '19 at 15:22
  • I want to learn order of java. I can't find related tutorial, all of tutorials show 2+2 = 4 like that. – Emre KÖK Dec 14 '19 at 15:24
  • @khelwood So, it goes to closest class to reference, bottom to top. Isn't it ? – Emre KÖK Dec 14 '19 at 15:26
  • @EmreKÖK That depends what you mean by "bottom" and "top" in this context. If you mean the furthest down the inheritance hierarchy, with superclass above subclasses, then yes. – khelwood Dec 14 '19 at 15:30
  • don't know why it gets so downvoted... anyany you (and me) got the answer from khelwood! just to mention, instead of printing one, two or three, why you don't print the type of the argument, i mean.. "A", "B" or "Object".. – Victor Dec 14 '19 at 17:27
  • @Victor It's my quiz question, i didn't think change it. – Emre KÖK Dec 14 '19 at 17:39
  • humble suggestion it was, you can't arguee is more straightforward – Victor Dec 14 '19 at 17:40

1 Answers1

1

Overloading will resolve to the most specific type that applies to the argument. All of A, B and Object could apply to C, but the most specific of those is B. So method(B) will be called.

If C did not extend A or B, then method(Object) would be called.

khelwood
  • 55,782
  • 14
  • 81
  • 108