Polymorphism¶
Polymorphism is a programming technique in which a seemingly single method can behave differently in different contexts. This technique will reduce the repeating codes and increase the code flexibility to the user of the method. As the definition suggests, the word polymorph means multiple forms.
The polymorphism only makes sense from the user's perspective, not from the creator of the method and operator. Consider the following picture where the user invokes speak() method that contained in the three different animal Objects. Each object contains a method with the same name ( speak ), and when used, results in a different outcome( Woof!, Meow!, Moo! ). This is polymorphism in a nutshell.
› Types of Polymorphism¶
In Java there is two ways to accomplish polymorphism.
- Compile-time Polymorphism
- Run-time Polymorphism
› Compile-time Polymorphism¶
The compile-time polymorphism can be achieved through method overloading and operator overloading in Java.
Method Overloading:
Remember in Java we can create methods with same name provided if they differ in parameters. We made sure that method signature of the methods are unique to ensure that it won't result in duplicate methods. For example,
It turns out, when you create a method with same name different signature, you are achieving polymorphism to the user of your method. Let's see this in example.
Let's say you took your time and created following useful methods in your Train class:
From the user's perspective, it feels they are using a single addOnePassenger() method, not 3 different methods, That is the main goal of polymorphism, to reduce the code duplications for the user, even if we deceive them, it simplifies their coding experience.