Wednesday, July 9, 2008

Polymorphism

Objects can respond differently to the same message (call of a method). Both waiter as kitchen respond to 'a black coffee' through prepare coffee method.
Action steps of this "prepare coffee" method of waiter and kitchen is different as given below.

Actions in Waiter's "prepare coffee" method
  • Pass the message to the kitchen.
  • Wait for response.
  • Delivers coffee and settles the account.
Actions in Kitchen's "prepare coffee" method
  • Kitchen brews fresh coffee
  • Passes it to the waiter.

As shown in above figure the same message with different implementations, that is polymorphism. The pseudo code representation of prepare method can be given as shown below

Class Waiter {
Prepare Coffee () {
Pass the message to the kitchen
Get
the response from kitchen
Settle the account
Deliver the coffee
}
}

Class Kitchen {
Prepare Coffee () {
Brews fresh coffee
Deliver the coffee to waiter
}
}

This type of polymorphism is called in several names like Single polymorphism, Overriding, Dynamic binding polymorphism, Late binding polymorphism

There is another type of polymorphism called Multiple polymorphism. This can be viewed as Object responding similarly for different types of messages.

In the above image two different messages are given as "money for black coffee" and "black coffee". Since the response is similar the action "prepare coffee" name is persevered. A parameter is introduced to the action (method) to distinguish the two types of messages. The pseudo code representation of prepare method can be given as shown below

Class Waiter {
Prepare Coffee () {
Pass the message to the kitchen
Get
the response from kitchen
Settle the account
Deliver the coffee
}

Prepare Coffee (money) {
Settle the account
Pass the message to the kitchen
Get
the response from kitchen
Deliver the coffee
}
}

This type of called by names like Overloading, Static binding polymorphism, Early binding polymorphism.
The Static binding and Early binding polymorphism names are used because the reference to a method occur at the compile time. In other words if following code is used in a Object Oriented language it will give an error because "kitchen" object does not have a "
Prepare Coffee (money)" method.

waiter.Prepare Coffee (money);
kitchen.Prepare Coffee (money);


Resources

1 comment:

Leo Sadeepa said...

Dear Viraj ,

Great to read your blog. First article itself is interesting ..

Expect to read more blog entries from you ... :)