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()
?
Advantages of PolymorphismIt helps the programmer to reuse the codes, i.e., classes once written, tested and implemented can be reused as required. Saves a lot of time. Single variable can be used to store multiple data types. Easy to debug the codes.
Polymorphism in C++ allows us to reuse code by creating one function that's usable for multiple uses. We can also make operators polymorphic and use them to add not only numbers but also combine strings. This saves time and allows for a more streamlined program.
Inheritance supports the concept of reusability and reduces code length in object-oriented programming. Polymorphism allows the object to decide which form of the function to implement at compile-time (overloading) as well as run-time (overriding).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With