Search code examples
javainheritancemethodsstaticoverload-resolution

Why is overloaded method selected with direct superclass parameter rather than Object?


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!


Solution

  • 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.