2

I'm confused in below examples. some one can please explain me why in Example 1 it will print "st" and in Example 2 give compile time ambiguity for non primitive types and non parent-child relations classes.

Example 1

public class FinalTest {
    public static void main(String[] args) {
        name(null);
    }

    public static void name(String s) {
        System.out.println("st");
    }

    public static void name(Object s) {
        System.out.println("obj");
    }
}

Example 2

public class FinalTest {
    public static void main(String[] args) {
        name(null);
    }

    public static void name(String s) {
        System.out.println("st");
    }

    public static void name(Integer s) {
        System.out.println("obj");
    }
}
Raj Bhatia
  • 1,049
  • 4
  • 18
  • 37
  • 1
    Possible duplicate of [Compiler error : reference to call ambiguous](http://stackoverflow.com/questions/14053596/compiler-error-reference-to-call-ambiguous) – Keyur Bhanderi Apr 15 '17 at 06:35
  • No its not duplicate, it may fall in same category but its a different scenario. – Raj Bhatia Apr 15 '17 at 06:57

1 Answers1

3

In Example 1 public static void name(String s) is more specific than public static void name(Object s). So the null in name(null); is supposed to be a String object being null.

But in Example 2 both public static void name(String s) and public static void name(Integer s) are equal in specific. So both method name(String) in FinalTest and method name(Integer) in FinalTest match for name(null);.

See 15.12.2.5. Choosing the Most Specific Method for a detailed description.

The following should work:

public class FinalTest {
    public static void main(String[] args) {
        String s = null;
        name(s);
        Object o = null;
        name(o);
        Integer i = null;
        name(i);
    }

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

    public static void name(Object s) {
        System.out.println("Object");
    }

    public static void name(Integer s) {
        System.out.println("Integer");
    }
}
Axel Richter
  • 56,077
  • 6
  • 60
  • 87