Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can null be passed to an overloaded Java method? [duplicate]

I found this Java code from this site. I don't understand how it compiles without ambiguous error.

 package swain.test;

 public class Test {
     public static void JavaTest(Object obj) {
         System.out.println("Object");
     }

     public static void JavaTest(String arg) {
         System.out.println("String");
     }

     public static void main(String[] args) {
         JavaTest(null);
     }
}

Output:

String
like image 921
Sitansu Avatar asked Aug 11 '15 06:08

Sitansu


People also ask

What happens if we pass null in a method in java?

When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn't happen unless we intentionally pass null value.

Can we pass null as argument in java?

So when you pass null as a parameter than compiler gets confused that which object method to call i.e. With parameter Object or parameter Integer since they both are object and their reference can be null. But the primitives in java does not extends Object.

Can the overloaded methods have the same return type?

No, you cannot overload a method based on different return type but same argument type and number in java. same name. different parameters (different type or, different number or both).

Is it possible to override overloaded method Why?

So can you override an overloaded function? Yes, since the overloaded method is a completely different method in the eyes of the compiler.


1 Answers

null can be passed to both JavaTest(String arg) and JavaTest(Object obj), so the compiler chooses the method with the more specific argument types. Since String is more specific than Object (String being a sub-class of Object), JavaTest(String arg) is chosen.

If instead of JavaTest(Object obj) you had JavaTest(Integer obj), the compilation would have failed, since Integer is not more specific than String and String is not more specific thanInteger`, so the compiler wouldn't be able to make a choice.

like image 191
Eran Avatar answered Nov 15 '22 00:11

Eran