Although, Polymorphism is already explained in great details in this post but I would like put more emphasis on why part of it.

Why Polymorphism is so important in any OOP language.

Let’s try to build a simple application for a TV with and without Inheritance/Polymorphism. Post each version of the application, we do a small retrospective.

Supposing, you are a software engineer at a TV company and you are asked to write software for Volume, Brightness and Colour controllers to increase and decrease their values on user command.

You start with writing classes for each of these features by adding

set:- To set a value of a controller.(Supposing this has controller specific code) get:- To get a value of a controller.(Supposing this has controller specific code) adjust:- To validate the input and setting a controller.(Generic validations.. independent of controllers) user input mapping with controllers :- To get user input and invoking controllers accordingly.

Application Version 1

import java.util.Scanner; class VolumeControllerV1 { private int value; int get() { return value; } void set(int value) { System.out.println("Old value of VolumeController \t"+this.value); this.value = value; System.out.println("New value of VolumeController \t"+this.value); } void adjust(int value) { int temp = this.get(); if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) { System.out.println("Can not adjust any further"); return; } this.set(temp + value); } } class BrightnessControllerV1 { private int value; int get() { return value; } void set(int value) { System.out.println("Old value of BrightnessController \t"+this.value); this.value = value; System.out.println("New value of BrightnessController \t"+this.value); } void adjust(int value) { int temp = this.get(); if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) { System.out.println("Can not adjust any further"); return; } this.set(temp + value); } } class ColourControllerV1 { private int value; int get() { return value; } void set(int value) { System.out.println("Old value of ColourController \t"+this.value); this.value = value; System.out.println("New value of ColourController \t"+this.value); } void adjust(int value) { int temp = this.get(); if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) { System.out.println("Can not adjust any further"); return; } this.set(temp + value); } } /* * There can be n number of controllers * */ public class TvApplicationV1 { public static void main(String[] args) { VolumeControllerV1 volumeControllerV1 = new VolumeControllerV1(); BrightnessControllerV1 brightnessControllerV1 = new BrightnessControllerV1(); ColourControllerV1 colourControllerV1 = new ColourControllerV1(); OUTER: while(true) { Scanner sc=new Scanner(System.in); System.out.println(" Enter your option

Press 1 to increase volume

Press 2 to decrease volume"); System.out.println(" Press 3 to increase brightness

Press 4 to decrease brightness"); System.out.println(" Press 5 to increase color

Press 6 to decrease color"); System.out.println("Press any other Button to shutdown"); int button = sc.nextInt(); switch (button) { case 1: { volumeControllerV1.adjust(5); break; } case 2: { volumeControllerV1.adjust(-5); break; } case 3: { brightnessControllerV1.adjust(5); break; } case 4: { brightnessControllerV1.adjust(-5); break; } case 5: { colourControllerV1.adjust(5); break; } case 6: { colourControllerV1.adjust(-5); break; } default: System.out.println("Shutting down..........."); break OUTER; } } } }

Now you have our first version of working application ready to be deployed. Time to analyze the work done so far.

Issues in TV Application Version 1

Adjust(int value) code is duplicate in all three classes. You would like to minimize the code duplicity. (But you did not think of common code and moving it to some super class to avoid duplicate code)

You decide to live with that as long as your application works as expected.

After sometimes, your Boss comes back to you and asks you to add reset functionality to the existing application. Reset would set all 3 three controller to their respective default values.

You start writing a new class (ResetFunctionV2) for the new functionality and map the user input mapping code for this new feature.

Application Version 2

import java.util.Scanner; class VolumeControllerV2 { private int defaultValue = 25; private int value; int getDefaultValue() { return defaultValue; } int get() { return value; } void set(int value) { System.out.println("Old value of VolumeController \t"+this.value); this.value = value; System.out.println("New value of VolumeController \t"+this.value); } void adjust(int value) { int temp = this.get(); if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) { System.out.println("Can not adjust any further"); return; } this.set(temp + value); } } class BrightnessControllerV2 { private int defaultValue = 50; private int value; int get() { return value; } int getDefaultValue() { return defaultValue; } void set(int value) { System.out.println("Old value of BrightnessController \t"+this.value); this.value = value; System.out.println("New value of BrightnessController \t"+this.value); } void adjust(int value) { int temp = this.get(); if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) { System.out.println("Can not adjust any further"); return; } this.set(temp + value); } } class ColourControllerV2 { private int defaultValue = 40; private int value; int get() { return value; } int getDefaultValue() { return defaultValue; } void set(int value) { System.out.println("Old value of ColourController \t"+this.value); this.value = value; System.out.println("New value of ColourController \t"+this.value); } void adjust(int value) { int temp = this.get(); if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) { System.out.println("Can not adjust any further"); return; } this.set(temp + value); } } class ResetFunctionV2 { private VolumeControllerV2 volumeControllerV2 ; private BrightnessControllerV2 brightnessControllerV2; private ColourControllerV2 colourControllerV2; ResetFunctionV2(VolumeControllerV2 volumeControllerV2, BrightnessControllerV2 brightnessControllerV2, ColourControllerV2 colourControllerV2) { this.volumeControllerV2 = volumeControllerV2; this.brightnessControllerV2 = brightnessControllerV2; this.colourControllerV2 = colourControllerV2; } void onReset() { volumeControllerV2.set(volumeControllerV2.getDefaultValue()); brightnessControllerV2.set(brightnessControllerV2.getDefaultValue()); colourControllerV2.set(colourControllerV2.getDefaultValue()); } } /* * so on * There can be n number of controllers * * */ public class TvApplicationV2 { public static void main(String[] args) { VolumeControllerV2 volumeControllerV2 = new VolumeControllerV2(); BrightnessControllerV2 brightnessControllerV2 = new BrightnessControllerV2(); ColourControllerV2 colourControllerV2 = new ColourControllerV2(); ResetFunctionV2 resetFunctionV2 = new ResetFunctionV2(volumeControllerV2, brightnessControllerV2, colourControllerV2); OUTER: while(true) { Scanner sc=new Scanner(System.in); System.out.println(" Enter your option

Press 1 to increase volume

Press 2 to decrease volume"); System.out.println(" Press 3 to increase brightness

Press 4 to decrease brightness"); System.out.println(" Press 5 to increase color

Press 6 to decrease color"); System.out.println(" Press 7 to reset TV

Press any other Button to shutdown"); int button = sc.nextInt(); switch (button) { case 1: { volumeControllerV2.adjust(5); break; } case 2: { volumeControllerV2.adjust(-5); break; } case 3: { brightnessControllerV2.adjust(5); break; } case 4: { brightnessControllerV2.adjust(-5); break; } case 5: { colourControllerV2.adjust(5); break; } case 6: { colourControllerV2.adjust(-5); break; } case 7: { resetFunctionV2.onReset(); break; } default: System.out.println("Shutting down..........."); break OUTER; } } } }

So you have your application ready with Reset feature. But, now you start realizing that

Issues in TV Application Version 2

If a new controller is introduced to the product, you have to change Reset feature code. If the count of the controller grows very high, you would have issue in holding the references of the controllers. Reset feature code is tightly coupled with all the controllers Class’s code(to get and set default values). Reset feature class (ResetFunctionV2) can access other method of the Controller class’s (adjust) which is undesirable.

At the same time, You hear from you Boss that you might have to add a feature wherein each of controllers, on start-up, needs to check for the latest version of driver from company’s hosted driver repository via internet.

Now you start thinking that this new feature to be added resembles with Reset feature and Issues of Application (V2) will be multiplied if you don’t re-factor your application.

You start thinking of using inheritance so that you can take advantage from polymorphic ability of JAVA and you add a new abstract class (ControllerV3) to

Declare the signature of get and set method. Contain adjust method implementation which was earlier replicated among all the controllers. Declare setDefault method so that reset feature can be easily implemented leveraging Polymorphism.

With these improvements, you have version 3 of your TV application ready with you.

Application Version 3

import java.util.ArrayList; import java.util.List; import java.util.Scanner; abstract class ControllerV3 { abstract void set(int value); abstract int get(); void adjust(int value) { int temp = this.get(); if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) { System.out.println("Can not adjust any further"); return; } this.set(temp + value); } abstract void setDefault(); } class VolumeControllerV3 extends ControllerV3 { private int defaultValue = 25; private int value; public void setDefault() { set(defaultValue); } int get() { return value; } void set(int value) { System.out.println("Old value of VolumeController \t"+this.value); this.value = value; System.out.println("New value of VolumeController \t"+this.value); } } class BrightnessControllerV3 extends ControllerV3 { private int defaultValue = 50; private int value; public void setDefault() { set(defaultValue); } int get() { return value; } void set(int value) { System.out.println("Old value of BrightnessController \t"+this.value); this.value = value; System.out.println("New value of BrightnessController \t"+this.value); } } class ColourControllerV3 extends ControllerV3 { private int defaultValue = 40; private int value; public void setDefault() { set(defaultValue); } int get() { return value; } void set(int value) { System.out.println("Old value of ColourController \t"+this.value); this.value = value; System.out.println("New value of ColourController \t"+this.value); } } class ResetFunctionV3 { private List<ControllerV3> controllers = null; ResetFunctionV3(List<ControllerV3> controllers) { this.controllers = controllers; } void onReset() { for (ControllerV3 controllerV3 :this.controllers) { controllerV3.setDefault(); } } } /* * so on * There can be n number of controllers * * */ public class TvApplicationV3 { public static void main(String[] args) { VolumeControllerV3 volumeControllerV3 = new VolumeControllerV3(); BrightnessControllerV3 brightnessControllerV3 = new BrightnessControllerV3(); ColourControllerV3 colourControllerV3 = new ColourControllerV3(); List<ControllerV3> controllerV3s = new ArrayList<>(); controllerV3s.add(volumeControllerV3); controllerV3s.add(brightnessControllerV3); controllerV3s.add(colourControllerV3); ResetFunctionV3 resetFunctionV3 = new ResetFunctionV3(controllerV3s); OUTER: while(true) { Scanner sc=new Scanner(System.in); System.out.println(" Enter your option

Press 1 to increase volume

Press 2 to decrease volume"); System.out.println(" Press 3 to increase brightness

Press 4 to decrease brightness"); System.out.println(" Press 5 to increase color

Press 6 to decrease color"); System.out.println(" Press 7 to reset TV

Press any other Button to shutdown"); int button = sc.nextInt(); switch (button) { case 1: { volumeControllerV3.adjust(5); break; } case 2: { volumeControllerV3.adjust(-5); break; } case 3: { brightnessControllerV3.adjust(5); break; } case 4: { brightnessControllerV3.adjust(-5); break; } case 5: { colourControllerV3.adjust(5); break; } case 6: { colourControllerV3.adjust(-5); break; } case 7: { resetFunctionV3.onReset(); break; } default: System.out.println("Shutting down..........."); break OUTER; } } } }

Although most of the Issue listed in issue list of V2 were addressed except

Issues in TV Application Version 3

Reset feature class (ResetFunctionV3) can access other method of the Controller class’s (adjust) which is undesirable.

Again, you think of solving this problem, as now you have another feature (driver update at startup) to implement as well. If you don’t fix it, it will get replicated to new features as well.

So you divide the contract defined in abstract class and write 2 interfaces for

Reset feature. Driver Update.

And have your 1st concrete class implement them as below

Application Version 4

import java.util.ArrayList; import java.util.List; import java.util.Scanner; interface OnReset { void setDefault(); } interface OnStart { void checkForDriverUpdate(); } abstract class ControllerV4 implements OnReset,OnStart { abstract void set(int value); abstract int get(); void adjust(int value) { int temp = this.get(); if(((value > 0) && (temp >= 100)) || ((value < 0) && (temp <= 0))) { System.out.println("Can not adjust any further"); return; } this.set(temp + value); } } class VolumeControllerV4 extends ControllerV4 { private int defaultValue = 25; private int value; @Override int get() { return value; } void set(int value) { System.out.println("Old value of VolumeController \t"+this.value); this.value = value; System.out.println("New value of VolumeController \t"+this.value); } @Override public void setDefault() { set(defaultValue); } @Override public void checkForDriverUpdate() { System.out.println("Checking driver update for VolumeController .... Done"); } } class BrightnessControllerV4 extends ControllerV4 { private int defaultValue = 50; private int value; @Override int get() { return value; } @Override void set(int value) { System.out.println("Old value of BrightnessController \t"+this.value); this.value = value; System.out.println("New value of BrightnessController \t"+this.value); } @Override public void setDefault() { set(defaultValue); } @Override public void checkForDriverUpdate() { System.out.println("Checking driver update for BrightnessController .... Done"); } } class ColourControllerV4 extends ControllerV4 { private int defaultValue = 40; private int value; @Override int get() { return value; } void set(int value) { System.out.println("Old value of ColourController \t"+this.value); this.value = value; System.out.println("New value of ColourController \t"+this.value); } @Override public void setDefault() { set(defaultValue); } @Override public void checkForDriverUpdate() { System.out.println("Checking driver update for ColourController .... Done"); } } class ResetFunctionV4 { private List<OnReset> controllers = null; ResetFunctionV4(List<OnReset> controllers) { this.controllers = controllers; } void onReset() { for (OnReset onreset :this.controllers) { onreset.setDefault(); } } } class InitializeDeviceV4 { private List<OnStart> controllers = null; InitializeDeviceV4(List<OnStart> controllers) { this.controllers = controllers; } void initialize() { for (OnStart onStart :this.controllers) { onStart.checkForDriverUpdate(); } } } /* * so on * There can be n number of controllers * * */ public class TvApplicationV4 { public static void main(String[] args) { VolumeControllerV4 volumeControllerV4 = new VolumeControllerV4(); BrightnessControllerV4 brightnessControllerV4 = new BrightnessControllerV4(); ColourControllerV4 colourControllerV4 = new ColourControllerV4(); List<ControllerV4> controllerV4s = new ArrayList<>(); controllerV4s.add(brightnessControllerV4); controllerV4s.add(volumeControllerV4); controllerV4s.add(colourControllerV4); List<OnStart> controllersToInitialize = new ArrayList<>(); controllersToInitialize.addAll(controllerV4s); InitializeDeviceV4 initializeDeviceV4 = new InitializeDeviceV4(controllersToInitialize); initializeDeviceV4.initialize(); List<OnReset> controllersToReset = new ArrayList<>(); controllersToReset.addAll(controllerV4s); ResetFunctionV4 resetFunctionV4 = new ResetFunctionV4(controllersToReset); OUTER: while(true) { Scanner sc=new Scanner(System.in); System.out.println(" Enter your option

Press 1 to increase volume

Press 2 to decrease volume"); System.out.println(" Press 3 to increase brightness

Press 4 to decrease brightness"); System.out.println(" Press 5 to increase color

Press 6 to decrease color"); System.out.println(" Press 7 to reset TV

Press any other Button to shutdown"); int button = sc.nextInt(); switch (button) { case 1: { volumeControllerV4.adjust(5); break; } case 2: { volumeControllerV4.adjust(-5); break; } case 3: { brightnessControllerV4.adjust(5); break; } case 4: { brightnessControllerV4.adjust(-5); break; } case 5: { colourControllerV4.adjust(5); break; } case 6: { colourControllerV4.adjust(-5); break; } case 7: { resetFunctionV4.onReset(); break; } default: System.out.println("Shutting down..........."); break OUTER; } } } }

Now all of the issue faced by you got addressed and you realized that with the use of Inheritance and Polymorphism you could

Keep various part of application loosely coupled.( Reset or Driver Update feature components don’t need to be made aware of actual controller classes(Volume, Brightness and Colour), any class implementing OnReset or OnStart will be acceptable to Reset or Driver Update feature components respectively). Application enhancement becomes easier.(New addition of controller wont impact reset or driver update feature component, and it is now really easy for you to add new ones) Keep layer of abstraction.(Now Reset feature can see only setDefault method of controllers and Reset feature can see only checkForDriverUpdate method of controllers)

Hope, this helps :-)