Java Reference
In-Depth Information
public void test(Employee e) {
System.out.println("Inside test(Employee e)");
}
public void test(Manager e) {
System.out.println("Inside test(Manager m)");
}
public static void main(String[] args) {
OverloadingTest ot = new OverloadingTest();
int i = 10;
int j = 15;
double d1 = 10.4;
double d2 = 2.5;
float f1 = 2.3F;
float f2 = 4.5F;
short s1 = 2;
short s2 = 6;
ot.add(i, j);
ot.add(d1, j);
ot.add(i, s1);
ot.add(s1, s2);
ot.add(f1, f2);
ot.add(f1, s2);
Employee emp = new Employee();
Manager mgr = new Manager();
ot.test(emp);
ot.test(mgr);
emp = mgr;
ot.test(emp);
}
}
Inside add(int a, int b)
Inside add(double a, double b)
Inside add(int a, int b)
Inside add(int a, int b)
Inside add(double a, double b)
Inside add(double a, double b)
Inside test(Employee e)
Inside test(Manager m)
Inside test(Employee e)
Note that the compiler knows only the compile-time type (the declared type) of the actual and the formal
parameters. Let's look at the
ot.add(f1, s2)
method call. The types of actual parameters are
float
and
short
.
There is no
add(float, short)
method in the
OverloadingTest
class. The compiler tries to widen the type of the
first argument to a
double
data type and it finds a match based on the first parameter
add(double, double)
.