Passing a null reference in a method parameter in java?

When I run this code, the output will be "String"; if I hide the method that takes the String parameter and runs the code again, then the output will be "Object", so can someone explain to 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);
    }
}
+4
source share
1 answer

The compiler will choose the most specific method, in this case String is a subclass of Object, so a method with String as an argument will be called.

From JLS 12.15.2.5

- , . Java , .

, , , , , , .

+8

Source: https://habr.com/ru/post/1541118/


All Articles