According to wikipedia , polymorphism is the provision of a single interface to entities of different types.[1] A polymorphic type is one whose operations can also be applied to values of some other type, or types.
More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language (OOPL)
An example of polymorphism :
Advantage of polymorphism:
One of the best practices of OOP is "program to interfaces". The overall meaning of this is to use interface types where you normally use concrete classes.
Let's take an example:
You need to write a class Payroll. It's responsibility is to generate payroll for employees of the organization. Let's try to solve this problem without using polymorphism first.
For a Manager, the method would like this:
public void generatePayroll(Manager manager)Now, for another kind of employee e.g. Accountant, there would be one more method like this:
public void generatePayroll(Accountant accountant)Can you notice a code smell here?
We are adding a method for every type of Employee. The code is tightly coupled.
Apart from redundancy in the code, there is a maintenance nightmare: update all methods in case the organization decides to change it's payroll process.
Polymorphism to the rescue:
The object hierarchy looks like this: Manager is a type of Employee, Accountant is another type of Employee.
So, we can define Manager, Accountant classes to extend/implement the Employee class. AND change the generatePayroll method to accept an argument of type Employee. So, the method signature would look like this:
public void generatePayroll(Employee employee)Result:
We have just removed the code smell. We no longer need to have the redundancy in code. If there is a change in the organization's payroll process, the change is minimal i.e. in only one method.
In future, your system might add another type of Employee. But you don't have to worry. The generatePayroll(Employee employee) method is already capable of handling it's payroll process.
This is one simple example. As your code grows complex, you would appreciate the importance of polymorphism more. Many design patterns use polymorphism as the key feature.
hope this helps please like my facebook page to get updated about my blogs....

No comments:
Post a Comment