The Java Program: Dispatch.java

  1 // Dispatch.java -- illustrates OO dynamic dispatch of methods
  2 
  3 class Base {
  4     void method() {
  5         System.out.println ("Base's method");
  6     }
  7 }
  8 
  9 class Derived extends Base {
 10     @Override
 11     void method() {
 12         System.out.println ("Derived's method");
 13     }
 14 }
 15 
 16 class Dispatch {
 17    public static void main (String args[]) {
 18 
 19       Base a = new Derived();
 20 
 21       /*
 22         The method actually invoked in the call below does
 23         not depend on the static type ("Base" in this case)
 24         of the variable ("a") known by the compiler, but
 25         on the value of the object at runtime, in this case
 26         an instance of class "Derived".
 27       */
 28 
 29       a.method();     // Derived's method called
 30 
 31     }
 32 }