Dynamic method dispatch

  • Dynamic method dispatch is a mechanism by which a call to an overrident method is resolved at run time instead of compile.

  • It is also called as Runtime polymerphism.

  • Let say a parent class contains a method that is overriden by child class. We generally create objects of parent class and child classes and a reference variable of parent class. Now, we can use reference variable of the parent class to point to parent class object or child class objects. The method called by using the reference variable will be of the parent/child object to whom currently the reference is pointing and not of the reference class.

Example : Dynamic Method Dispatch

Example:Dispatch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class A {
 
    void display() {
 
        System.out.println("this is class A");
 
    }
}
 
class B extends A {
 
    void display() {
 
        System.out.println("this is class B");
 
    }
}
 
class C extends A {
 
    void display() {
 
        System.out.println("this is class C");
 
    }
}
 
public class Dispatch {
 
    public static void main(String arg[]) {
 
        A a = new A();
 
        B b = new B();
 
        C c = new C();
 
        A ref; //reference variable
 
        ref = a; //ref refers to class A object
 
        ref.display(); //ref calls A's version of display();
 
        ref = b; //ref refers to class C object
 
        ref.display(); //ref calls B's version of display();
 
        ref = c; //ref refers to class C object
 
        ref.display(); //ref calls C's version of display();
 
    }
}

 

 

OUTPUT:

this is class A

this is Class B

this is class C

Last modified: Saturday, 14 April 2012, 08:18 AM

Skip Navigation

Navigation

Skip OpenGurukulSkip Settings

Settings