Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing null reference in a method parameter in java? [duplicate]

Tags:

java

string

When i run this code the output is "String"; if I hide the method that accepts a String parameter and run the code again then the output is "Object", so can anyone please explain me how this code works?

public class Example {

    static void method(Object obj) {
        System.out.println("Object");
    }

    static void method(String str) {
        System.out.println("String");
    }  

    public static void main(String args[]) {
        method(null);
    }
}
like image 788
varun Avatar asked Feb 13 '23 22:02

varun


1 Answers

Compiler will choose most specific method, in this case, String is a sub class of Object, so the method with String as argument will be invoked.

From JLS 15.12.2.5

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.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

like image 150
Abimaran Kugathasan Avatar answered Feb 15 '23 13:02

Abimaran Kugathasan