Question

public class test {
public static void main(String[] args) {
    magic(null);
}

public static void magic(String s) {
    System.out.println("String passed");
}

public static void magic(Object o) {
    System.out.println("object passed");
}
}

why string passed printed not object passed.

Was it helpful?

Solution

From JLS

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.

OTHER TIPS

When you don't type cast, it is chosen upon the most specific. null can be reference of type String or an Object. So, if both are available then the String method will be called.

public class test {
    public static void main(String[] args) {
        magic(null);
    }

    public static void magic(Object o) {
        System.out.println("object passed");
    }

    public static void magic(String s) {
        System.out.println("String passed");
    }

    public static void magic(Integer s) {
        System.out.println("Integer passed");
    }
}

This would no longer compile,

It would say : Ambiguous method call. Both magic(String) and magic(Integer) in test match

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top