OOP Concepts: Polymorphism
A practical guide with Java
Polymorphism is one of the four pillars of object-oriented programming. Here in this article, we will talk about the 2 types of polymorphism, how it can be used in Java and how to use super keyword. So let’s get started!
In object-oriented programming, polymorphism is the ability of an object to exist in many different forms.
Java supports 2 types of polymorphism.
- Compile-time polymorphism
- Run-time polymorphism
Compile-time polymorphism
This is also called as static polymorphism. In this type the compiler determines which method should be executed. In Java, it is a situation that occurs when methods in the same class share the same name but with differences in the argument list. Argument lists could be different when there is,
1.Different number of parameters
Ex:- one method accepts 2 parameters and the other method accepts 3 parameters
2.Different data types of parameters
Ex:- one method accepts an int type parameter and another accepts a String type parameter
3.Parameters in a different order
Ex:- one method accepts a String and a double and another accepts a double and a String. But this kind of overloading is not recommended.
Let’s consider a scenario of when I want to display the details of a person. But sometimes I may not have all the required details. So I want a program that allows me to display details of the person with whatever detail I have at the time.
Here in this program if I enter only a name then showDetails(String name) method is called. But if I enter both name and age then showDetails(String name, int age) method is called and so on.
This is the output.
Run-time polymorphism
This is called method overriding or dynamic polymorphism as well. Declaring a method in a subclass that is already present in the parent class is known as method overriding. Here the JVM (Java Runtime Environment) determines which method should be executed.
For method overriding the method signature: method name, parameter list, and return type have to be matched exactly.
To understand this concept let’s take Food as the superclass and Noodles and Cake as subclasses.
I have taken as food is normally cooked. But for cake, there is an exception. The cake should be baked not cooked. So I have implemented make(String name) method in Cake class again including the specific features of Cake class. So here when I call the make() function for an object of type Cake the make(String name) method in superclass Food is overridden by make(String name) method in subclass Cake.
Here is the output.
Super keyword
Consider superclass Doctor and subclass Surgeon. And here I want to give surgeon, the normal functionality of a doctor in making treatments and also I want to give functionality specific to the surgeon as well.
The output is shown here.
I hope this article helped you to get a clear understanding of polymorphism.
Happy Coding!