Benefit of Polymorphism [closed]
Solution 1:
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
Solution 2:
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.)
Solution 3:
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();
Solution 4:
The reason that you want to use
CoolingMachines cm = new Refrigerator();
is that you can later easily use a different CoolingMachines
. You only need to change that one line of code and the rest of the code will still work (as it will only use methods of CoolingMachines
, which is more general than a specific machine, such as a Refrigerator
).
So for a particular instance of Refrigerator
, the calls cm.start();
and rf.start()
work the same way but cm
might also be a different CoolingMachines
object. And that object could have a different implementation of start()
.
Solution 5:
First answer:
Use polymorphism for method overridding and method overloading. Other class methods used in different class then two options: first method inherited, second method over written. Here extend interface: use them, or implemention method: logic write them. Polymorphism used for method, class inheritance.
Second answer:
Is there any difference between cm.start();
and rf.start();
?
Yes, both are objects that are completely different with respect to each other. Do not create interface objects because Java doesn`t support interface objects. First object created for interface and second for Refrigerator class. Second object right now.