Using your objects polymorphically also helps to create factories or families of related classes which is an important part of how Factory Design Pattern is implemented. Here's a very basic example of polymorphic factory:
public CoolingMachine CreateCoolingMachines(string machineType)
{
if(machineType == "ref")
return new Refrigerator();
//other else ifs to return other types of CoolingMachine family
}
usage of calling above code:
CoolingMachine cm = CreateCoolingMachine("AC"); //the cm variable will have a reference to Airconditioner class which is returned by CreateCoolingMachines() method polymorphically
Also, imagine that you have a method as below that uses concrete class parameter Refrigerator
:
public void UseObject(Refrigerator refObject)
{
//Implementation to use Refrigerator object only
}
Now, if you change above implementation of UseObject()
method to use most generic base class parameter, the calling code would get advantage to pass any parameter polymorphically which can then be utilized inside the method UseObject()
:
public void UseObject(CoolingMachine coolingMachineObject)
{
//Implementation to use Generic object and all derived objects
}
Above code is now more extensible as other subclasses could be added later to the family of
CoolingMachines, and objects of those new subclasses would also work with the existing code.