Java Method Dynamic Dispatch

Introduction

Dynamic method dispatch is how Java implements run-time polymorphism.

Here is an example that illustrates dynamic method dispatch:

// Dynamic Method Dispatch
class A {//from w w w. j a va  2s  .  c  o m
   void callme() {
     System.out.println("Inside A's callme method");
  }
}

class B extends A {
  // override callme()
  void callme() {
    System.out.println("Inside B's callme method");
  }
}

class C extends A {
  // override callme()
  void callme() {
    System.out.println("Inside C's callme method");
  }
}

public class Main {
  public static void main(String args[]) {
    A a = new A(); // object of type A
    B b = new B(); // object of type B
    C c = new C(); // object of type C
    A r; // obtain a reference of type A    

    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
  }
}

Using run-time polymorphism to calculate area of various shapes.


// Using run-time polymorphism.
class Shape {
  double width;/*  w w w.j  a  va  2  s.  c  o  m*/
  double height; 

  Shape(double a, double b) {
    width = a;
    height = b;
  }

  double area() {
    System.out.println("Area for Shape 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 width * height;
  }
}

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 width * height / 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());
  }
}



PreviousNext

Related