Reputation: 2081
public class test {
public static void main(String[] args) {
magic(null);
}
public static void magic(String s) {
System.out.println("String passed");
}
public static void magic(Object o) {
System.out.println("object passed");
}
}
why string passed printed not object passed.
Upvotes: 3
Views: 91
Reputation: 141
When you don't type cast, it is chosen upon the most specific.
null
can be reference of type String
or an Object
.
So, if both are available then the String method will be called.
public class test {
public static void main(String[] args) {
magic(null);
}
public static void magic(Object o) {
System.out.println("object passed");
}
public static void magic(String s) {
System.out.println("String passed");
}
public static void magic(Integer s) {
System.out.println("Integer passed");
}
}
This would no longer compile,
It would say : Ambiguous method call. Both magic(String)
and magic(Integer)
in test match
Upvotes: 1
Reputation: 32468
From JLS
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
Upvotes: 4