asit said:
public class Test1{
static void method(Object obj){
System.out.println("Object");
}
static void method(String str){
System.out.println("String");
}
public static void main(String args[]){
method(null);
}
Here why the output is String ???
The JLS explains this in detail under §15.12. I will elide discussion of
the first step, as that merely identifies the candidate methods using a
method that ignores types of arguments.
The second step filters them out into a list of methods that satisfy the
subtyping arguments. null is a subtype of all reference types. The last
part of §15.12.2.2 has this sentence:
[T]he most specific method (§15.12.2.5) is chosen among the methods that
are applicable by subtyping.
The discussion continues under §15.12.2.5 as follows:
One fixed-arity member method named m is more specific than another
member method of the same name and arity if all of the following
conditions hold:
* The declared types of the parameters of the first member method
are T1, . . . , Tn.
* The declared types of the parameters of the other method are U1,
.. . . , Un.
[...]
* For all j from 1 to n, Tj <: Sj.
[ That is to say, a method is more specific than another if its type
arguments are all subtypes of the other's. ]
A method m1 is strictly more specific than another method m2 if and only
if m1 is more specific than m2 and m2 is not more specific than m1.
A method is said to be maximally specific for a method invocation if it
is accessible and applicable and there is no other method that is
applicable and accessible that is strictly more specific.
If there is exactly one maximally specific method, then that method is
in fact the most specific method; it is necessarily more specific than
any other accessible method that is applicable. It is then subjected to
some further compile-time checks as described in §15.12.3.
In short, the String method is more specific than the Object method, so
the compiler chooses that. If there was another method that had, say, an
Integer argument.
The way to pick the correct method is to do a cast to the type you
want--e.g., Object.