Dynamic Method Dispatch

Dynamic Method dispatch is a well known term in java technology and mainly part of theoretical concept but used very often in the programming. To consider more in deep let’s consider an example.

class Fruit {

	public String name() {
		return "Any Fruit";
	}
}

class Mango extends Fruit {

    @Override
	public String name() {
		return "Mango";
	}
}

public class FruitSeller {

	public static void main(String args[]) {
		Fruit fruit = new Mango();
		String fruitName = fruit.name();
		System.out.println(fruitName);
	}
}

Here, we have created classes Mango and Fruit where Mango is subclass of Fruit and Mango overrides name method according to it’s purpose. Now, let’s consider the Dynamic Method Dispatch, it is made of three words Dynamic, Method and Dispatch which means ‘Find Method At Runtime’. Just look at the class FruitSeller, here following statement is doing something different than regular Object creation with new keyword,

Fruit fruit = new Mango();

Which means ‘create a Mango with the help of Fruit’ but when we call method fruit.name() it states get name of Fruit but here note that fruit is a reference of the Fruit and not Mango(which extends the Fruit).

Dynamic Method Dispatch stands for finding the method to call at run time.

In above case you will have following output,

Mango

When you call the method with the reference of Parent class Java internally detects which method to call at runtime based on the Object that reference refers to. In other way Java takes decision at runtime to call actual method based on the Object (Here Mango) even though the reference is Fruit.

DMDBlog

Here we are creating Object with the reference of Parent so we are up casting the Object of child class which is completely valid while following is not valid as we are trying to downcast child to the parent which is not allowed.

Mango mango = new Fruit();

Here it becomes incompatible to cast, because here every mango is a Fruit but every Fruit is not Mango. So, to create Mango you can use Fruit but Fruit which can be Apple, Banana, Cherry can not be created by Mango. Here note that down casting will be allowed by Java if that succeed during runtime

Dynamic Method Dispatch is also called Runtime Polymorphism

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s