Java will always try to
use the most specific applicable version of a method that's available.
public class TestOverload {
public static void main(String[] args) {
method1(null);
}
/* If below uncommented, then
compiler gives
compile time Ambiguous
exception. */
/*static void
method1(TestOverload obj){
System.out.println("TestOverload "+obj);
}*/
static void method1(Object obj){
System.out.println("Object "+obj);
}
/* Since Object is super type
of String , so String
* is more specific than
Object*/
static void method1(String obj){
System.out.println("String "+ obj);
}
}
Output:
String null
Scenario 2:
public static void doSomething(Object obj) {
System.out.println("Object
called");
}
public static void doSomething(char[] obj) {
System.out.println("Array
called");
}
public static void doSomething(Integer obj) {
System.out.println("Integer
called");
}
Java will
always try to use the most specific applicable version of a method that's
available (see JLS
§15.12.2).
Object, char[] and Integer can
all take null as a valid value. Therefore all 3 version are
applicable, so Java will have to find the most specific one.
Since Object is
the super-type of char[], the array version is more specific than
the Object-version. So if only those two methods exist, the char[] version
will be chosen.
When both
the char[] and Integer versions are available, then both of
them are more specific than Object but none is more specific than the
other, so Java can't decide which one to call. In this case you'll have to
explicitly mention which one you want to call by casting the argument to the
appropriate type.
On the
contrary, the following invocation would be perfectly unambiguous:
char[] x = null;
doSomething(x);
Although
you're still passing the value null, Java knows exactly which method to
call, since it will take the type of the variable into account.
Scenario 3 :
Scenario 3 :
class Overload {
void print(Integer i) {
System.out.println("Integer
called");
}
void print(String i) {
System.out.println("String
called");
}
void print(Object i) {
System.out.println("Object
called");
}
}
Overload obj= new Overload();
obj.print(null);
The method print(Integer) is ambiguous for the type Overload
Here String and Object are compatible or Integer and Object are compatible. Since Integer and String are of same priority , it creates ambiguity.
Scenario 4:
System.out.println(null);
The method println(char[]) is ambiguous for the type PrintStream
No comments:
Post a Comment