Week 17 lecture topics

Method overriding & Polymorphism

.

The foregoing leads to an interesting problem as illustrated by the following program :-


   /* Demonstration of polymorphic referencing
      Author P. Martin
      Date 14/12/99
   */
   public class Application {

      public static void main(String [] args){
        Vehicle v;                   //a variable capable of refering to a 
                                     //Vehicle or Car or ...
        v = new Vehicle("ABC 123");  //now refers to a Vehicle
        v.display();                 //should invoke Vehicle version of display

        v = new Car("PQR 111",4);    //now it refers to a Car
        v.display();                 //now it should invoke the Car version of
                                     //display()
      } //end main()

   } //end class Application

The problem faced by the compiler (and the programmer) is that in general we will not know what type of object a variable refers to, so when we send it a message like display() which differs in implementation from one class to another, we wont know which one should be called.

The compiler solves the problem by postponing the decision until the call is executed at run time and it is able to find out what v refers to. This is called dynamic or run-time binding.

The programmer solves the problem by making sure that all versions of display() do the same basic operation but in different ways that suit the different object types involved. (e.g. saying SIT to a dog may evoke different behaviour depending on the type of dog concerned).

This is OK so long as the different behaviours are equivalent.

A situation in which a method name can refer to one of a number of different versions of a method implementation in different classes where each implementation does different but equivalent things is called polymorphism.

Note very carefully :-

It is in the case of overriding that we need to use dynamic-binding and to provide polymorphic methods.