Dynamic Method Dispatch in java programming language. || What is dynamic method dispatch? || dynamic method dispatch in java. || dynamic method dispatch



Dynamic Method Dispatch

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. a super-class reference variable can refer to a subclass object. Java uses this fact to resolve calls to overridden methods at run time. Here is how. When an overridden method is called through a super-class reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. When different types of objects are referred to, different versions of an overridden method will be called. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed. Therefore, if a super-class contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different versions of the method are executed.

Example:


class superClass //create a superclass

{

void show()//method to be overridden

{ System.out.println("This is superClass method."); }

}

class subClassA extends superClass

{

void show()

{ System.out.println("This is subClassA method."); }

}

class subClassB extends superClass

{

void show()

{ System.out.println("This is subClassB method."); }

}

class DynamicMethodDispatch

{

public static void main(String args[])

{

superClass supObj = new superClass(); //creates a superclass object

subClassA subObjA = new subClassA(); //creates a subclassA object

subClassB subObjB = new subClassB();//creates a subclassB object

supObj.show(); //this will call a superclass method

supObj = subObjA; //subclass reference is assigned to superclass ref.

//Here Dynamic Method Dispatch occurred and will call a subClassA method.

supObj.show();

supObj = subObjB; //subclass reference is assigned to superclass ref.

//Here Dynamic Method Dispatch occurred and will call a subClassB method.

supObj.show();

}

}

1 Comments

Please do not enter any spam link in the comment box

Post a Comment

Please do not enter any spam link in the comment box