Forums Register Login
null passed as parameter
public class Test1{
static void method(String str){
static void method(Object obj){
public static void main(String args[]){

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

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,

looks like I was beaten to it!

Selecting the Most Specific Method
thanks gowher,daniel and wise...that helped me to get my feet in water..now tryin to swim...
This is also addressed in our SCJP FAQ.

This thread has been viewed 725 times.

All times above are in ranch (not your local) time.
The current ranch time is
Nov 14, 2018 16:47:11.