3
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.

1

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In partiular, if you'd add (say) void magic(Integer s), then the program wouldn't compile anymore, since then it would be ambigous as to what the more specific method would be.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.