2

I have the following structure of my class:

void add(String s){
    System.out.println("string");
}

void add(Object s){
    System.out.println("object");
}

public static void main(String[] args) {
    new MyClazz().add(null);
}

O/P : string

Why object is not called?

xyz
  • 2,160
  • 3
  • 20
  • 31
  • [So](http://stackoverflow.com/q/1572322/1393766) [many](http://stackoverflow.com/q/13133177/1393766) [duplicates](http://stackoverflow.com/q/5229809/1393766). – Pshemo Jun 14 '15 at 11:36
  • you may find more using https://stackoverflow.com/search?q=%5Bjava%5D+overload+method+call+null – Pshemo Jun 14 '15 at 11:54

1 Answers1

2

String is more specific than Object. Therefore void add(String s) is preferred over void add(Object s).

15.12.2. Compile-Time Step 2: Determine Method Signature

The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is the one used at run time to perform the method dispatch.

Eran
  • 387,369
  • 54
  • 702
  • 768