aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes null as parameter Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "null as parameter" Watch "null as parameter" New topic
Author

null as parameter

kanchan chaudhary
Greenhorn

Joined: Jun 06, 2001
Posts: 28
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

Joined: Jun 01, 2001
Posts: 51
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

Joined: Feb 26, 2001
Posts: 4742
    
    7

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).]


Junilu - [How to Ask Questions] [How to Answer Questions]
 
wood burning stoves
 
subject: null as parameter