Benefit of Polymorphism

khan picture khan · Jun 18, 2012 · Viewed 24k times · Source

When I started to look for the benefits of polymorphism, I found with this question here. But here I was unable to find my answer. Let me tell what I want to find. Here I have some classes:

class CoolingMachines{
    public void startMachine(){
        //No implementationion
    }
    public void stopMachine(){
        //No implementationion
    }
}

class Refrigerator extends CoolingMachines{
    public void startMachine(){
        System.out.println("Refrigerator Starts");
    }
    public void stopMachine(){
        System.out.println("Refrigerator Stop");
    }
    public void trip(){
        System.out.println("Refrigerator Trip");
    }
}

class AirConditioner extends CoolingMachines{
    public void startMachine(){
        System.out.println("AC Starts");
    }
    public void stopMachine(){
        System.out.println("AC Stop");
    }
}

public class PolymorphismDemo {
    CoolingMachines cm = new Refrigerator();
    Refrigerator rf = new Refrigerator();
}

Now here I created two objects in the Demo class and are references of Refrigerator. I have completely understood that from the rf object I am able to call the trip() method of Refrigerator, but that method will be hidden for the cm object. Now my question is why should I use polymorphism or why should I use

CoolingMachines cm = new Refrigerator();

when I am OK with

Refrigerator rf = new Refrigerator();

Is polymorphic object's efficiency is good or light in weight? What is the basic purpose and difference between both of these objects? Is there any difference between cm.start(); and rf.start()?

Answer

pgras picture pgras · Jun 18, 2012

It is useful when you handle lists... A short example:

List<CoolingMachines> coolingMachines = ... // a list of CoolingMachines 
for (CoolingMachine current : coolingMachines) {
    current.start();
}

Or when you want to allow a method to work with any subclass of CoolingMachines