So here it is this example
public static void main(String[] args) {
new Stuff(null);
new Stuff("a");
new Stuff(1);
}
and class Stuff is defined as follow
public class Stuff {
Stuff(Object o){
System.out.println("object");
}
Stuff(String s){
System.out.println("string");
}
}
The output is
string
string
object
How does Java tell the null
is a String
? If I change Stuff
to
public class Stuff {
Stuff(String s){
System.out.println("string");
}
Stuff(Integer o){
System.out.println("Integer");
}
}
I get compilation error for Stuff(null)
:
The constructore Stuff(String) is ambigous.
Again, why does Java "decide" null
is a String
?
In Java, null is a literal, a special constant you can point to whenever you wish to point to the absence of a value. It is neither an object nor a type, which is a common misconception newcomers to the Java language have to grapple with.
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.
You cannot pass the null value as a parameter to a Java scalar type method; Java scalar types are always non-nullable. However, Java object types can accept null values.
The Null object is a special instance of a class which represents missing value. If some method expects an object as a parameter, you can always pass the Null object representation without worry it will cause an unexpected exception at the runtime.
String
is a subclass of Object
and is therefore more specific.The full algorithm to determine which method should be chosen is defined in the JLS.
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