I have the following code
import java.util.List;
public class Sample {
public static void main(String[] args) {
test(null);
}
static void test(List<Object> a){
System.out.println("List of Object");
}
static void test(Object a){
System.out.println("Object");
}
}
and I got following output in console
List of Object
Why doesn't this call test(Object a)
? Can you some one explain how it took "List as" null
?
You can pass NULL as a function parameter only if the specific parameter is a pointer. The only practical way is with a pointer for a parameter.
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.
In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.
In a nutshell, the most specific method among the overloads is chosen.
In this case the most specific method is the one that takes List<Object>
since it's a subtype of Object
.
The exact algorithm Java uses to pick overloaded methods is quite complex. See Java Language Specification section 15.12.2.5 for details.
Always specific first, in cases like that. If you change List to String, it will print the same thing. Every class is child of Object, so if it have to overload, will be to the more specific class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With