Good question Kishan.
Look at the following code.
class Test1 {
public static void main(String args[]) {
Test1
test = new Test1();
C c = new C();
test.tester(c);
}
public void tester(A a) {
System.out.println("Class A ");
}
public void tester(B b) {
System.out.println("Class B");
}
// Commented out for clarity.!!
/*
public void tester(C c) {
System.out.println("Class C");
}
*/
}
class A {
}
class B extends A {
}
class C extends B {
}
------------------------------------------------
The output is "Class B", because there is no method which takes
a variable of type "C", the next choice is "tester(B b)".
because, type "C" extends from type "B".
[ the "type" of the variable reference
is important not the class of the object when a method is called, clarified
with an example show below ]
So.. for such overloaded ( overloaded with types that extends another)
methods, the if the compiler can't find an
exact match for the variable's type, it goes for the most specific one,
as above.
In ur example, the compiler thinks the method
"public void method(String s)" is more specific than
"public void method(Object s)", for the "null" type !!. ( i know "why" is ur question !!)
( "null" type !! eh !)
[ now, if u add another method as u did in ur example, Mr. compiler
gets confused.... rite ?? , there will be two eligible candidates !]
------------------------------------------------
The "type" of the variable reference
is important not the class of the object when a method is called, clarified
with an example show below
------------------------------------------------
class Test1 {
public static void main(String args[]) {
Test1 test = new Test1();
C c = new C();
test.tester(c);
B b = new C();
test.tester(b);
}
public void tester(A a) {
System.out.println("Class A ");
}
public void tester(B b) {
System.out.println("Class B");
}
public void tester(C c) {
System.out.println("Class C");
}
}
class A {
}
class B extends A {
}
class C extends B {
}
------------------------------------------------
The output is
- "Class C"
- "Class B"
------------------------------------------------
Did it help ??
Correct me if am wrong.