Java: Ambicious method call

Ambicious method call error occurs when Java compiler doesn't know which of the overloaded method to call. Let's assume that we have the following overloaded methods: first method accepts the String parameter and prints it. The second method accepts Integer parameter and also prints it.

public void print(String param) {
    System.out.println("Printing parameter + "param" + " as String");
}

and

public void print(Integer param) {
    System.out.println("Printing parameter + " + param  + " as Integer");
}

Calling one of the methods into the following way print(null) will attempt to the error like this:

Error:(16, 17) java: reference to print is ambiguous
  both method print(java.lang.String) in MainApp and method print(java.lang.Integer) in MainApp match

Such error occurs because null is a special reference type in Java. To escape such error we need to cast null either to String or to Integer:

print((String)null)

Here we're casting null to String. As a result the method with String input parameter will be called and the following message will be printed on console:

Printing parameter null as String

Alexey Bogdanov

Read more posts by this author.

Subscribe to Development notes

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!