Polymorphism

Monday, January 14, 2008

Polymorphism

Polymorphism


Another benefit of separating implementaion from behavior is polymorphism. Polymorphism allows two or more objects respond to the same message. A method called name could also be implemented for an object of the class Course. Even though the implementation of this name message may return a course number and a course title, its protocol is the same as the name message to the Student object. Polymorphism allows a sending object to communicate with different objects in a consistant manner without worrying about how many different implementations of a message.

An analogy of polymorphism to daily life is how students response to a school bell. Every student knows the significant of the bell. When the bell (message) rings, however, it has its own meaning to different students (objects). Some students go home, some go to the library, and some go to other classes. Every student responds to the bell, but how they response to it might be different.

Another example of polymorphism is the function of printing. Every printable object must know how to print itself. The message is the same to all the different objects: print, but the actual implementation of what they must do to print themselves varies.

The sending object does not have to know how the receiving object implement the message. Only the receiving objects worries about that. Assume that there is a printPage method in a Document object that has the responsibility of printing a page. To print the page, the printPage method sends the print message to each object on the page. The Document does not need to know what types of objects are on the page, only that each object supports the behavior of printing.

New objects can be added to the page without affecting the printPage method. This method still sends the print message and the new object provides its own print method in response to that message.

Polymorphism allows the sending object to communicate with receiving objects without having to understand what type of object it is, as long as the receiving objects support the messages.

0 comments:

 

Tamil Video Songs | Make Money Online