Polymorphism (Cont.)


An Example of Runtime Polymorphism
The following program creates one superclass called A and its two subclasses B and C. These subclasses override the m1 method.

  1. Inside the main method in Dispatch class, initially objects of types A, B, and C are declared:
       A a = new A( );
       B b = new B( );
       C c = new C( );
  1. Now a reference of type A, called ref, is also declared. Initially it will point to null.
       A ref;  // Obtain a reference of type A.
  1. Now we are assigning the reference ref by the objects (A, B, or C) one-by-one, and use that reference to invoke m1. The version of m1 executed is determined by the type of object being referred to at the time of the call.
       ref = a;
       // ref refers to an A object.
       ref.m1( );
       // Calling A's version of m1( )
    
       ref = b;
       // Now ref refers to a B object.
       ref.m1( );
       // Calling B's version of m1( )
    
       ref = c;
       // Now ref refers to a C object.
       ref.m1( );
       // Calling C's version of m1( )





Dispatch.java (dynamic method dispatch)
// Dynamic method dispatch using hierarchical inheritance 
// Driver class
class Dispatch {
  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 ref;            // Obtain a reference of type A.

    ref = a;          // ref refers to an A object.
    ref.m1( );        // Calling A's version of m1( )
    ref = b;          // Now ref refers to a B object.
    ref.m1( );        // Calling B's version of m1( )
    ref = c;          // Now ref refers to a C object
    ref.m1( );        // Calling C's version of m1( ).
  }
}
class A { 
  void m1( ) { System.out.print( "A" ); } 
} 
class B extends A { 
  // Overriding m1( ) 
  void m1( ) { System.out.print( "B" ); } 
} 
class C extends A { 
  // Overriding m1( ) 
  void m1( ) { System.out.print( "C" ); } 
}
shell> java Dispatch

Output:           Result: