1

I have seen questions on Stack Overflow about a method overloading for null argument but didn't solve my confusion and I tried something different which was not discussed in there answers that's why asking this question.

I want the reason when I pass "null" it executes the function whose argument type is double and when I pass "0" or any other numeric digit like 1,2,10 etc to the function it executes the function whose argument type is "Object". I know there is a difference in NULL and 0 here is the difference.

Thanks!

Code:

public class NullArgumentOverloading {

    public static void main(String[] args) {

        NullArgumentOverloading obj = new NullArgumentOverloading();
        obj.overLoad(null); // prints "Double array argument method."
        obj.overLoad(0); // prints "Object o argument method."
    }

    private void overLoad(Object o) {
        System.out.println("Object o argument method.");
    }

    private void overLoad(double[] dArray) {
        System.out.println("Double array argument method.");
    }
}
Joker
  • 2,304
  • 25
  • 36
AmeeQ
  • 117
  • 1
  • 3
  • 12
  • 2
    Because `0` gets autoboxed into `Integer` which is not a `double[]` but an `Object`. – daniu Dec 18 '18 at 11:43
  • ok fine but why double argument get execute when we pass null to the function. – AmeeQ Dec 18 '18 at 11:47
  • Because it uses the most specific method possible, and `double[]` is more specific than `Object`. – daniu Dec 18 '18 at 11:50
  • hmmm, Thanks!!! – AmeeQ Dec 18 '18 at 11:55
  • @daniu correct me if I am wrong when I pass 0 the wrapper class converts it into Integer which is a subclass of Object that's why it executes Object argument and when I pass "null" in the arguments it is more specific to an array because it referring to some memory slot which is empty. – AmeeQ Dec 18 '18 at 12:00

1 Answers1

4

Java will always try to use the most specific version of a method that's available (see JLS 15.12.2).

Object, double[] can both take null as a valid value. Therefore both are suitable.

Object is the super-type of double[] and therefore more specific than just Object. So thats the reason why it prints "Double array argument method." when you pass null to the function

For the ohter Question: As already explained in the comments, when you pass 0 which is a primitive int, will be boxed automatically into an Integer which have Object as super-type, so it prints "Object o argument method."

You can find more info in Method Overloading for null argument

Joker
  • 2,304
  • 25
  • 36