Using your objects polymorphically also helps to create factories or families of related classes, which is an important part of how the Factory design pattern . Here is a very simple example of a polymorphic factory:
public CoolingMachine CreateCoolingMachines(string machineType) { if(machineType == "ref") return new Refrigerator();
using call over code:
CoolingMachine cm = CreateCoolingMachine("AC");
Also imagine that you have a method as shown below that uses a specific parameter of the Refrigerator class:
public void UseObject(Refrigerator refObject) {
Now, if you change the implementation of the UseObject() method UseObject() to use the most general parameter of the base class, the calling code will have the advantage of passing any parameter, polymorphically, which can then be used inside the UseObject() method:
public void UseObject(CoolingMachine coolingMachineObject) {
The above code is now more extensible, since other subclasses can be added later to the CoolingMachines family and the objects of these new subclasses will also work with existing code.
VS1 Jun 18 2018-12-12T00: 00Z
source share