1

Why does the following code print "string"? Why is there no error because the method call is ambiguous?

class Mixer {
    void print(String s) {
        System.out.println("string");
    }

    void print(Object o) {
        System.out.println("object");
    }


    public static void main(String[] args) {
        Mixer m = new Mixer();
        m.print(null);
    }
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Sourabh
  • 119
  • 1
  • 9

1 Answers1

2

Explanation

The String-method is chosen because it is the most specific of those types.

Since both methods would be accessible and applicable Java selects the most specific of both, this is described in the Java Language Specification in detail.

See JLS§15.12.2 which says:

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.

JLS§15.12.2.5 lists all rules that are used to determine the most specific method.


Example

Take a look at the following methods:

public void foo(Object o) { ... }
public void foo(AbstractCollection<String> o) { ... }
public void foo(AbstractList<String> o) { ... }
public void foo(ArrayList<String> o) { ... }

With each method the specified type gets more specific, if you give an ArrayList or null it will thus first use the lowest method.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82