0

This question is bothering me for a while.Please help

Suppose there are two methods

public void add(Object obj){
/* some logic*/
}

public void add(String str){
/*Some logic*/
}

so when i call add(null) which method will get executed and why?

thanks

2
  • Add the language tag.
    – Yu Hao
    Jun 30, 2014 at 4:56
  • but on what bases jvm considers most specfic type?its still unclear to me
    – vikrant
    Jun 30, 2014 at 5:03

2 Answers 2

2

In this case the String argument version wins, because String is a more specific type as every class is a subclass of Object (except itself).

Anyway, you'll still be able to call the Object argument version by casting.

e.g.

app.add((Object) null);

If there're more than one potential match, such as having a version of add(Integer i) version available, it's an error, and won't compile.

2
  • if specific type wins then what about this add(Integer sum) and add(String str)?
    – vikrant
    Jun 30, 2014 at 5:17
  • @vicky, then it won't compile, updated the answer.
    – ryenus
    Jun 30, 2014 at 5:23
1

It will call method with String argument...

classes in Java are direct or indirect subclasses of Object. So String is a subtype of Object, the method overloaded to accept a String is more specific than the method overloaded to accept an Object. A String can be converted (upcast) to Object, but an Object cannot be converted (downcast or upcast) to String, so the method taking the String argument is more specific. Therefore, print(String s) will be invoked by the call print(null).

Not the answer you're looking for? Browse other questions tagged or ask your own question.