![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
Dynamic method dispatch is a mechanism by which java implements runtime polymorphism. Using this a call to an overridden method is resolved at runtime rather than at compile time.
Java uses the fact that a superclass reference varaible can refer to a subclass object.Thus java determines call to a overriden methods at run time.
Suppose an overridden method is called by superclass reference, java resolves which version of method as per type of object being reffered to at the time of call occures. This is done at the run time.
The method to be executed is determined at run time depends on object referred at the time of call.
Following example shows the The version of display method executed is determined by the type of object being reffered to at the time of call.
class A { void display() { System.out.println("I'm display 1"); } } class B extends A { void display() { System.out.println("I'm display 2"); } } class dispatch> { public static void main(String args[]) { A a1 = new A(); B b1 = new B(); A a2; // obtaining a reference of class A a2 = a1; // a2 referes to an a1 object a2.display(); // call class A version of display method a2 = b2; a2.display(); } }
In above example, class A is the superclass of B. the subclass B overrides the method display declared in A. In main method a1,b1 are two objects created. Also one referrence of class A is created.The program assigns the reference to each object from a2 object to invoke dispaly method.