-2

I have this code :

class A{}
class B extends A{}
class C extends B{}
class D{
    public void m(B b){
        System.out.println("A");
    }
    public void m(Object o){
        System.out.println("B");
    }
    public void m(String s){
        System.out.println("C");
    }
    public static void main(String args[]){
        D x = new D();
        x.m(null);
    }
}

I know this gives a compilation error. Compiler is confused among the results "A" and "C". Why null is extending from class B and String ?

  • 2
    `Why null is extending from class B and String ?` say whatt? – sam Oct 26 '15 at 15:38
  • At a guess - just a guess, mind you - I'd say the compiler knows it can fall back on "B" if it knows that (for example) the argument were an `Integer`. But because it's `null`, it doesn't know if "A" or "C" are applicable. It knows B is applicable, but B is kind of the fallback option. – dcsohl Oct 26 '15 at 15:40
  • This topic is not new, there are tons of questions and posts explaining this. – Luiggi Mendoza Oct 26 '15 at 15:43

1 Answers1

1

compiler is confused because you have three m() methods, and all of them can accept null reference. you need to explicitly tell which m() you want to call by casting the null to the desired argument like this x.m((String)null);

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
  • Actually, just two methods can be chosen – Alex Salauyou Oct 26 '15 at 15:48
  • @SashaSalauyou the three of them can be chosen because all of them receive an object reference. – Luiggi Mendoza Oct 26 '15 at 15:54
  • @LuiggiMendoza No, only two--as there are two leaves in class hierarchy covering arguments (`String` and `B`). To prove this, create 3 overloaded methods, every of which accept child of another, say, `Object`, `CharSequence` and `String`--and you'll see no disambugation even when passing null (as one can guess, `String`-arg method will be selected for execution). – Alex Salauyou Oct 27 '15 at 05:11