4

I have this code:

class SuperClass {

    int method(Object o){
        return 1;
    }

    int method(String s){
        return 2;
    }
}
public class PassingNull extends SuperClass {

    int method(Object s) {
        return 3;
    }
    public static void main(String... a){
        SuperClass sc = new SuperClass();
        PassingNull sb = new PassingNull();
        SuperClass st = new PassingNull();
        System.out.println(sc.method(null)); //1
        System.out.println(sb.method(null)); //2
        System.out.println(st.method(null)); //3
    }
}

I understand that for 1 and 3, it prints '2' because that most specific parameter type is called. But not able to understand why 2 prints '2'.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
Anushree Acharjee
  • 854
  • 5
  • 15
  • 30
  • 1
    My guess would be it's the same reason why 1 and 3 print `2`: it's using `method(String)` rather than your overriden `method(Object)` – Vince Mar 03 '15 at 04:59

1 Answers1

3

Basically, for the same reason as cases 1 and 2.

SuperClass has two methods named method, as you know. One of them takes an Object and the other takes a String, and the latter is more specific -- so passing null refers to the second (more specific) method, since null is applicable to both.

Now, PassingNull also has two methods named method. Like before, one overload takes Object (the one that overrides SuperClass::method(Object)), and the other one takes String (the one that's inherited straight from SuperClass). So it's a similar situation, meaning that the type resolution will work similarly: given that both overloads are applicable, the more specific one -- the one that takes String -- is the one that will get invoked.

yshavit
  • 42,327
  • 7
  • 87
  • 124