Overloading v/s Overriding methods…
class Operator {
public int operation(int x, int y) {
System.out.println(“First method invoked from parent class.”);
return x + y;
}
public double operation(double x, double y) {
System.out.println(“Second method invoked from parent class.”);
return x + y;
}
}
class ChildOperator extends Operator {
public int operation(int x, int y) {
// overriding method operation().
System.out.println(“First method invoked from child class.”);
return x + y;
}
public int operation () {
// overloading method operation().
return 0;
}
}
public class TestOverloading {
public static void main(String a[]) {
Operator op = new Operator();
// here object type and reference type both are Operator.
double ans1 = op.operation(5, 5);
System.out.println(ans1);
int ans2 = (int) op.operation(5.0, 8.0);
System.out.println(ans2);
double ans3 = op.operation(5.0, 8.0);
System.out.println(ans3);
Operator opChild = new ChildOperator();
// Reference type is Operator and object type is ChildOperator.
opChild.operation(5, 5);
// supertype method will be invoked.
}
}
/* The reference type will decide which method will be invoked in overloading at compile time…not object type.
* The Object type will decide which method will be invoked in overriding at run time…not reference type.
* */