This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Customer Requirements for Developers and have Marcho Behler on-line!
See this thread for details.
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 Customer Requirements for Developers this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "null as parameter" Watch "null as parameter" New topic

null as parameter

kanchan chaudhary

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();
Can anyone explain why the output is "String version"?
Haining Mu
Ranch Hand

Joined: Jun 01, 2001
Posts: 51
The rule stated in JLS 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

Joined: Feb 26, 2001
Posts: 6264

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.
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)
public void method(C o)
System.out.println("C version");
WhichOne x = new WhichOne();
x.method(null); // prints out "C version"

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]
It is sorta covered in the JavaRanch Style Guide.
subject: null as parameter
It's not a secret anymore!