previous  next 

Java -- Dynamic Dispatch

© Eileen Head, Leslie C. Lander, 2002

Purpose:  To see experience dynamic dispatching via an example  
Goal:  To understand how to use sub-typing polymorphisms in an object oriented language.

Dynamic (runtime) dispatching -- Important feature of any object oriented language

Which code is used?
class Animal {
    void move(Animal x ) {
        . . .
    }
}
class Bird extends Animal {
Animal ted ;
. . .
void fly( ){
ted = new Animal( );
ted.move(ted);
ted = new Bird( );
ted.move(ted);
}
}
Dynamic Dispatching: 
What is the Static Type and Dynamic Type?
Which code is used, code1 or code2?
class Animal { 
 void move(Animal x){
       code 1
 }
}
class Bird extends Animal {
Animal ted;    // static type ??
. . .
void move(Animal x ) { code 2 }
void fly( ){
ted = new Animal( ); // type ??
this.move(ted);  // uses code ?
ted.move(ted);   // uses code ?
ted = new Bird( ); // type ??
this.move(ted); // uses code ?
ted.move(ted);  // uses code ?
}
}
  • Different code is executed!
  • The determination of which code is used is made at run-time depending on the dynamic type of the OBJECT.
  • WHAT happens?

    Doug's Dilemma
    class Animal {
        ... 
        void move(Animal x ) { 
            CODE 1 
        } 
        ... 
    }
    class Mammal extends Animal {
    Animal ted;
    . . .
    void move(Mammal x )  { CODE 2 } // ? function
    void move(Animal x )  { Code 3 } // ? function
    void fly( ){
    ted = new Animal( );
    this.move(ted);  // code ? XQTd
    ted.move(ted);   // code ? XQTd
    ted = new Mammal( );
    this.move(ted); // code ? XQTd
    ted.move(ted);  // code ? XQTd
    Mammal fred = new Mammal();
    fred.move(fred);  // code ?
    this.move(fred);  // code ?
    ted.move(fred);   // code ?
    }
    }