Benefit of Polymorphism [closed] Benefit of Polymorphism [closed] java java

Benefit of Polymorphism [closed]


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


In cases where you're really okay with knowing the concrete class, there's no benefit. However, in many cases you want to be able to write code which only knows about the base class or interface.

For example, look at Iterables in Guava - that's a lot of methods which (mostly) don't care what implementation of Iterable is being used. Would you really want all that code separately for every implementation?

Where you can code to an abstract base class or an interface, you allow yourself to later use other implementations which share the same public API, but may have different implementations. Even if you only want a single production implementation, you may well want alternative implementations for testing. (The extent to which this applies very much depends on the class in question.)


Because later if you want to use AirConditioner instead of Refrigerator for cooling, then only code you need to change is CoolingMachines cm = new AirConditioner();