2
public class Overloading {
    public static void main(String[] args) {
        Overloading o = new Overloading();
        o.display(null);
    }
    void display(String s) {
        System.out.println("String method called");
    }
    void display(Object obj) {
        System.out.println("Object method called");
    }
}

It is giving the output as "String method called". I need the explanation why?

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
vinod kumar
  • 175
  • 2
  • 3
  • 6

2 Answers2

5

Taken from the Java Spec:

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.

First of all: both methods are accessible (obviously) and applicable. They are both applicable, because null is of type nulltype, which is by definition a subtype of all types. String is more specific than Object, because String extends Object. If you would add the following, you will have a problem, because both Integer and String are equally "specific":

void display(Integer s) {
    System.out.println("Integer method called");
}
noone
  • 19,520
  • 5
  • 61
  • 76
4

Java will always find the most specific version of method that is available.

String extends Object, and therefore it is more specific.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5

Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215