Lecture 14 - Dynamic Method Dispatch
Lecture 14 - Dynamic Method Dispatch
Method Overriding...
• In a class hierarchy, when a method in a subclass has
the same name and type signature as a method in its
superclass, then the method in the subclass is said to
override the method in the superclass.
class SuperClassDemo
{
public static void staticMethod()
{
System.out.println("SuperClassDemo staticMethod called");
}
}
class SubClassDemo extends SuperClassDemo
{
public static void staticMethod()
{
System.out.println("SubClassDemo staticMethod called");
}
public static void main(String []args){
SuperClassDemo superObj= new SuperClassDemo();
SuperClassDemo superobj1= new SubClassDem();
SubClassDemo subObj= new SubClassDem();
class Dispatch {
public static void main(String args[]) {
A a = new A(); B b = new B(); C c = new C();
A r; r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); } } // calls C's version of callme
Method Overriding...
Ex. class Figure {
double dim1; double dim2;
Figure(double a, double b) { dim1 = a; dim2 = b; }
double area() {
System.out.println("Area for Figure is undefined."); return 0;
} }
class Rectangle extends Figure {
Rectangle(double a, double b) { super(a, b); }
double area() { System.out.println("Inside Area for Rectangle.");
return dim1 * dim2; }}
class Triangle extends Figure {
Triangle(double a, double b) { super(a, b); }
double area() { System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2; } }
class FindAreas {
public static void main(String args[]) {
Method Overriding...
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure 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()); } }