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

Sharp Edge
  • 4,144
  • 2
  • 27
  • 41
vikrant
  • 399
  • 3
  • 12

2 Answers2

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.

ryenus
  • 15,711
  • 5
  • 56
  • 63
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).

user2408578
  • 464
  • 1
  • 4
  • 13