Well in biology Polymorphism is the ability of an organism or specie can have many different forms or stages. in object oriented programming. same concept goes with programming, An object can exist in many forms.
Let's say you have this Employee class.
public class Employee{
public int computeSalary(){
//How would you compute the salary of an average employee
}
}
Next is you have a subclass called BasePlusComission Employee
public class BasePlusCommissionEmployee extends Employee{
public int computeSalary(){
//Commision employee salary computation + Base Employee salary computation
}
}
And you have this CommissionEmployee
public class CommissionEmployee extends Employee{
public int computeSalary(){
//Commision employee salary computation
}
}
Now, we want to handle the computation of this Employees polymorphically. we can do
public void computeEmployeeSalary(Employee emp){
emp.computeSalary();
}
This method will receive any kind of Employee object(which means that we can pass a subclass of the Employee object). Once you have passed it, it will compute the passed employee (the argument) and it's computeSalary() will be called,
Even though you pass a BasePlusCommission Employee, or CommissionEmployee, it will compute its salary depending on its implementation thanks to Dynamic method look up.
Another clearer explanation. you can create a set or an array of employees.
Employee[] employees = { new BasePlusComissionEmployee(), new CommissionEmployee,new Employee()};
and you want these objects to compute their salary. you can handle their computation polymorphically like this
for(int i = 0; i < employees.length;i++){
employees[i].computeSalary();
}
Take note that Even though the arrays declaration is Employee their computeSalary()
implementation will vary depending on each class implementation of computeSalary();
of each objects of the employee array