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.
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( );
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.
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( )