Pages

Wednesday, January 5, 2011

Dynamic Method Dispatch in Java

In computer science dynamic dispatch is the process of mapping a message to a specific sequence of code/method at runtime.

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run-time, rather than compile time.

Example that demonstrates dynamic method dispatch.
class SuperClassA {
  void display() {
    System.out.println("In SuperClassA display()");
  }
}
class SubClassB extends SuperClassA {
      void display() {
        System.out.println("In SubClassB display()");
      }
}
class SubClassC extends SuperClassA {
  void display() {
    System.out.println("In SubClassC display()");
  }
}
class DMDispatch {
  public static void main(String args[]) {
    SuperClassA a = new SuperClassA();
    SubClassB b = new SubClassB();
    SubClassC c = new SubClassC();
    SuperClassA ref; // obtain a reference of type A

    ref = a; // ref refers to an SuperClassA object
    ref.display(); // calls SuperClassA's version of display()

    ref = b; // ref refers to a SubClassB object
    ref.display(); // calls SubClassB's version of display()

    ref = c; // ref refers to a SubClassC object
    ref.display(); // calls SubClassC's version of display()
  }
}
output:
In SuperClassA display()
In SubClassB display()
In SubClassC display()

No comments:

Post a Comment