Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the output for the following Java program where null is passed as argument for the overloaded methods? [duplicate]

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?

like image 297
vinod kumar Avatar asked Nov 25 '25 03:11

vinod kumar


2 Answers

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");
}
like image 91
noone Avatar answered Nov 26 '25 17:11

noone


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

like image 45
Oh Chin Boon Avatar answered Nov 26 '25 17:11

Oh Chin Boon