2
public class HelloWorld{
     public static void main(String []args){
        new SampleString().add(null);
     }
}

class SampleString{
    public void add(Object s){
        System.out.println("Inside Object method");
    }
    public void add(String s){
        System.out.println("Inside string method");
    }
}

Why does the program print "Inside string method" and not "Inside Object method" ? Can you please explain me the logic behind this ?

Mshnik
  • 7,032
  • 1
  • 25
  • 38
Sourav
  • 31
  • 3

2 Answers2

1

The compiler picks the most specific implementation based on the type of the argument passed to the method.

From the Java Language Specification section on determining compile-time method signature:

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

M A
  • 71,713
  • 13
  • 134
  • 174
  • 2
    I suspect the best section to quote from is actually 15.12.2.5 – Jon Skeet Jan 22 '15 at 17:49
  • @JonSkeet Thanks for the correction. I've been looking for that one. – M A Jan 22 '15 at 17:51
  • Thanks @Neil Locketz manouti. If i have two classes suppose A and B which both extends C. And then i pass add(A a) and add(B b) and then in the main method call add(null). Which one shall be printed ? – Sourav Jan 22 '15 at 17:55
  • 1
    @Sourav You'd get a compiler error due to ambiguity. This is also explained in the provided link. – M A Jan 22 '15 at 17:59
  • Thanks for the answers and the reference link. – Sourav Jan 22 '15 at 18:25
0

It will choose the highest level type that applies. Since String extends Object it becomes the highest level. If you call it with something that isn't a String it should use the Object one

Neil Locketz
  • 4,228
  • 1
  • 23
  • 34
  • 1
    "Highest level" isn't a very specific term. It would be better if you could use the same terminology as the language specification. – Jon Skeet Jan 22 '15 at 17:48