Google+

Like Us On Facebook


Total Pageviews

111. Dynamic Method Dispatch







Dynamic Method Dispatch is the mechanism by which a call to an overridden method is resolved at run time. In Dynamic Method Dispatch the overridden methods are called using reference objects. If we have to call the overridden method in the superclass, a reference object will be created for the superclass and the method in the superclass will be called using the object created. The same applies for other  sub-classes, we've to create objects for the classes and call the overridden methods using the created objects.

Lets implement this on Eclipse IDE:

1. Create superclass 'ClassA' containing sample( ) method as shown below and save:



2. Create subclass 'ClassB' which overrides sample( ) method in superclass 'ClassA' as shown below and save:



3. Create subclass 'ClassC' which overrides sample( ) method in superclass 'ClassB' as shown below and save:



4. Create 'CallOverridenMethodsUsingReferene' class to call the overriden methods of all the classes in the hierarchy by creating reference objects for all the classes as shown below:



5. Save and Run the 'CallOverridenMethodsUsingReference' class
6. Observe that the output is displayed in console as shown below:



After looking at the output, its very clear that we can call the overridden methods of all the classes in the  hierarchy by creating reference objects for all the classes during run time.

Download this project:

Click here to download the project containing the 'ClassA', 'ClassB' , 'ClassC' and 'CallOverriddenMethodsUsingReference' class files used in this post (You can download the project and import into Eclipse IDE on your machine)






Please comment below to feedback or ask questions.

'Abstract Classes' will be explained in the next post.





No comments:

Blog Index