Polymorphism in Java
What is Polymorphism?
Polymorphism refers to many forms, or it is a process that performs a single action in different ways.
Real-life Illustration for Polymorphism is:
A person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person possesses different behavior in different situations. This is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms.
Polymorphism in java can be classified into two types:
- Compile-Time Polymorphism
- Runtime Polymorphism
What is Compile-Time Polymorphism in Java?
It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
Method Overloading:
When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by changes in the number of arguments or/and a change in the type of arguments.
What is Runtime Polymorphism in Java?
It is also known as Dynamic Polymorphism. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.
Method Overriding:
In Java, method overriding occurs when a subclass (child class) has the same method as the parent class. In other words, method overriding occurs when a subclass provides a particular implementation of a method declared by one of its parent classes.
Advantages of Polymorphism in Java:
- Increases code reusability by allowing objects of different classes to be treated as objects of a common class.
- Improves readability and maintainability of code by reducing the amount of code that needs to be written and maintained.
- Supports dynamic binding, enabling the correct method to be called at runtime, based on the actual class of the object.
- Enables objects to be treated as a single type, making it easier to write generic code that can handle objects of different types.
Disadvantages of Polymorphism in Java:
- Can make it more difficult to understand the behavior of an object, especially if the code is complex.
- May lead to performance issues, as polymorphic behavior may require additional computations at runtime.