• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

null as parameter

 
kanchan chaudhary
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class AQuestion
{
public void method(Object o)
{
System.out.println("Object Verion");
}
public void method(String s)
{
System.out.println("String Version");
}
public static void main(String args[])
{
AQuestion question = new AQuestion();
question.method(null);
}
}
Can anyone explain why the output is "String version"?
Thanks
kanchan
 
Haining Mu
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The rule stated in JLS 15.12.2.2 is: Choose the Most Specific Method. So in your case, String is extends from Object, passed 'null' is more close to String than Object. Similarly, if your method para. are Integer and Number, Integer is choosed, but if you have String and Integer, it will be compile error because neither String nor Integer is more specific to each other.
 
Junilu Lacar
Bartender
Posts: 7606
54
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Very interesting...
Did a few experiments and it seems that Java will always go for the bottom-most class in a hierarchy (Object <-- String), (A <-- B <-- C). It complains about ambiguity when the parameters are not directly related.
<pre>
class A {}
class B extends A {}
class C extends B {}
class WhichOne
{
public void method(A o)
{
System.out.println("A version");
}
public void method(B o)
{
System.out.println("Bersion");
}
public void method(C o)
{
System.out.println("C version");
}
}
WhichOne x = new WhichOne();
x.method(null); // prints out "C version"
</pre>

Haven't found anything in the JLS to suggest this though... will keep looking... Oh, looks like Haining Mu found it.

[This message has been edited by JUNILU LACAR (edited June 07, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic