• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

null as parameter

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic