Thursday, June 2, 2011

Oops Concepts - Polymorphism

Polymorphism

This refers to the ability to assume different forms. In OOP, it indicates a language’s ability to handle objects differently based on their runtime type.
When objects communicate with one another, we say that they send and receive messages. The advantage of polymorphism is that the sender of a message doesn’t need to know which class the receiver is a member of. It can be any arbitrary class. The sending object only needs to be aware that the receiving object can perform a particular behavior.

A classic example of polymorphism can be demonstrated with geometric shapes. Suppose we have a Triangle, a Square, and a Circle. Each class is a Shape and each has a method named Draw that is responsible for rendering the Shape to the screen.

With polymorphism, you can write a method that takes a Shape object or an array of Shape objects as a parameter (as opposed to a specific kind of Shape). We can pass Triangles, Circles, and Squares to these methods without any problems, because referring to a class through its parent is perfectly legal. In this instance, the receiver is
only aware that it is getting a Shape that has a method named Draw, but it is ignorant of the specific kind of Shape. If the Shape were a Triangle, then Triangle’s version of Draw would be called. If it were a Square, then Square’s version would be called, and so on.

We can illustrate this concept with a simple example. Suppose we are working on a small graphics package and we need to draw several shapes on the screen at one time. To implement this functionality, we create a class called Scene. Scene has a method named Render that takes an array of Shape objects as a parameter. We can now create an array of different kinds of shapes and pass it to the Render method. Render can iterate through the array and call Draw for each element of the array, and the appropriate version of Draw will be called. Render has no idea what specific kind of Shape it is dealing with.

The big advantage to this implementation of the Scene class and its Render method is that two months from now, when you want toadd an Ellipse class to your graphics package, you don’t have to touch one line of code in the Scene class. The Render method can draw an Ellipse just like any other Shape because it deals with them generically. In this way, the Shape and Scene classes are loosely coupled, which is something you should strive for in a good object-oriented design.

This type of polymorphism is called parametric polymorphism , or generics. Another type of polymorphism is called overloading. Overloading occurs when an object has two or more behaviors that have the same name. The methods are distinguished only by the messages they receive (that is, by the parameters of the method). Polymorphism is a very powerful concept that allows the design of amazingly flexible
Applications.

No comments: