0

I am trying one simple method overloading in java but I cannot figure out the behaviour of "null" when passed as argument . Or I guess I am missing some theoretical aspect of overloading . Below is my code :

public class MethodOverloadNull {
    String met1(Object o) {
        System.out.println("In Objecct O");
        return "hello";
    }

    String met1(String o) {
        System.out.println("In String");
        return "hello";
    }

    public static void main(String[] args) {
        MethodOverloadNull obj=new MethodOverloadNull();
        obj.met1(null);
    }
}

Output is : In String.

But when I commented out overloaded String arg method I am getting output as : In Object O.

public class MethodOverloadNull {
    String met1(Object o) {
        System.out.println("In Object O");
        return "hello";
    }

    /*
    String met1(String o) { // commented this method 
        System.out.println("In String");
        return "hello";
    }
    */

    public static void main(String[] args) {
        MethodOverloadNull obj=new MethodOverloadNull();
        obj.met1(null);
    }
}

Output : In Object O

Why is this behaviour ???

NatNgs
  • 874
  • 14
  • 25
Rishav
  • 103
  • 7
  • 1
    java always looks for a more concrete object and enters that one first. – user2914191 Aug 12 '17 at 15:47
  • Why bother? Method overloading is resolved at *compile time*. This means the `null` problem exists only if you pass a *literal `null`* as parameter. And if you do so in real life code you should be beaten as hard as possible anyway... ;o) – Timothy Truckle Aug 12 '17 at 15:58

0 Answers0