Dynamic Method Dispatch
When an overridden method is called through a superclass reference, Java determines which version of that method to execute.
Here is an example that illustrates dynamic method dispatch:
class Base {
void callme() {
System.out.println("Inside A's callme method");
}
}
class SubClass extends Base {
void callme() {
System.out.println("Inside B's callme method");
}
}
class SubClass2 extends Base {
void callme() {
System.out.println("Inside C's callme method");
}
}
public class Main {
public static void main(String args[]) {
Base a = new Base();
SubClass b = new SubClass();
SubClass2 c = new SubClass2();
Base r;
r = a;
r.callme();
r = b;
r.callme();
r = c;
r.callme();
}
}
The output from the program is shown here:
Inside A's callme method
Inside B's callme method
Inside C's callme method
polymorphism
The following example use the run-time polymorphism.
class Shape {
double height;
double width;
Shape(double a, double b) {
height = a;
width = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}
}
class Rectangle extends Shape {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return height * width;
}
}
class Triangle extends Shape {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return height * width / 2;
}
}
public class Main {
public static void main(String args[]) {
Shape f = new Shape(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Shape figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
The output from the program is shown here:
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
Area for Figure is undefined.
Area is 0.0