Home           J2EE Concepts           JMS           Java Language           Contact           Back           Next           Bookmark this Page          










Some useful tips related to:
 - health & fitness
 - vehicle care
 - cooking
 - misc household tasks

Dynamic Method Dispatch


Before understanding what is Dynamic Method Dispatching, it is important to know that in Java a superclass reference variable can refer to a subclass object.

For example, you can create a generic class "Human" as parent class, and then "Student", "Employee" can be created as children classes.
Pseudo code for above example is shown below:

class Human{
  String name;
  public String getName(){
return name;
}
  public void disp(){
System.out.println("Human");
}
}

class Student extends Human{
  int rollNo;
  getRollNo{
return rollNo;
}
  public void disp(){
System.out.println("Student");
}
}

class demo{
  public static void main(){
Human h = new Human();
Student s = new Student();
h = s;
// more pseudo code here
}
}

At first glance it might seem that above code would throw compile time error because h & s are two different types of objects; but it actually is a perfectly valid code.
However, the variable h won't be able to access member variable rollNo aur method getRollNo() because it has not defined those. Stating this example in a generic manner: when reference of a subclass object is assigned to a superclass reference variable, the superclass variable will be able to access only those methods/members of the object that are defined by the superclass only.

 

Now coming to Dynamic Method Dispatching: it is a mechanism with help of which call to an overriden method is resolved at runtime rather than compile time.

Considering above example again:
class demo{
  public static void main(){
Human h = new Human();
Student s = new Student();
h.disp(); // This would print "Human"
h = s;
h.disp(); // This would print "Student"
}
}

This means that runtime behavior is determined on basis of the type of the object being referred to. This is one of the most powerful features of Java: you may have any no. of subclasses, with their own implementation of different methods & yet all could be referrenced through same variable based upon runtime circumstances.