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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "null passed as parameter" Watch "null passed as parameter" New topic
Author

null passed as parameter

amal shah
Ranch Hand

Joined: May 05, 2006
Posts: 92
public class Test1{
static void method(String str){
System.out.println("String");
}
static void method(Object obj){
System.out.println("Object");
}
public static void main(String args[]){
method(null);
}
}

o/p is: String

when method(null) is called ...then why method(String) is invoked and why not method(Object)...the fundamentals are Object and String can both accept null values....unable to understand...help appreciated..

thanking you
amal shah
Gowher Naik
Ranch Hand

Joined: Feb 07, 2005
Posts: 643
Because String is most specific then object.
Check the code below.

i am passing Child object to method now all 3 methods can take Child object
so all three methods match.But 3rd method is choosen by compiler because it is more specific then other 2 methods.
if you will remove 3rd method from above code then 2nd method will match and out put will be
SubClass Msg
lly if you will remove 2nd and 3rd method from above code then only method will remain is first method and compile will make match with 1st method
which has only choice left for comiler.
Daniel Bryant
Ranch Hand

Joined: Jul 15, 2006
Posts: 54
Hi,

I always think it's better to figure these problems out yourself rather than being explicitly told, and so at the risk of answering a question with a question, have a look at this code:



Compile and run it and see what output you get. Now experiment by commenting out the "method" methods above, one at a time and observe what happens to the output.

Can you see what's going on with the hierarchy of classes? Does this answer your question?

Best wishes,

Daniel


SCJP 1.4,<br />SCJD (URLyBird 1.2.1, JDK 5.0)
Daniel Bryant
Ranch Hand

Joined: Jul 15, 2006
Posts: 54
looks like I was beaten to it!

Daniel
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Selecting the Most Specific Method
amal shah
Ranch Hand

Joined: May 05, 2006
Posts: 92
thanks gowher,daniel and wise...that helped me to get my feet in water..now tryin to swim...
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

This is also addressed in our SCJP FAQ.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: null passed as parameter