Polymorphism using Overloading and Overriding in Java
Polymorphism is one of the fundamental principles of Object-Oriented Programming (OOP). It allows a single interface to represent different types of actions. Java supports two types of polymorphism:
- Compile-time polymorphism (Method Overloading)
- Runtime polymorphism (Method Overriding)
We have already covered Method Overriding and Dynamic Method Dispatch in detail. In this blog, we will explore both Method Overloading and how it works alongside Overriding in achieving polymorphism in Java.
Method Overloading (Compile-Time Polymorphism)#
Method overloading in Java allows multiple methods to have the same name but different parameters. The compiler determines which method to call based on the method signature (number and type of parameters).
Example of Method Overloading#
Expected Output:#
Key Points about Method Overloading:#
- Overloaded methods must have different parameter lists.
- The return type can be different, but it does not determine overloading.
- It improves code readability and reusability.
- It occurs at compile time, making it compile-time polymorphism.
Method Overriding (Runtime Polymorphism)#
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method in the subclass must have the same signature as in the superclass.
Example of Method Overriding#
Expected Output:#
Key Points about Method Overriding:#
- The method name and parameters must match exactly with the superclass method.
- The method in the subclass should have the same return type or a subtype.
- It occurs at runtime, making it runtime polymorphism.
- The
@Override
annotation is used to indicate an overridden method.
Polymorphism using Overloading and Overriding#
Both overloading and overriding contribute to achieving polymorphism in Java:
- Method Overloading provides flexibility by allowing multiple methods with the same name but different parameters within the same class.
- Method Overriding allows dynamic method invocation, enabling different behaviors based on the object type at runtime.
Example Demonstrating Both Overloading and Overriding#
Expected Output:#
Conclusion#
In this blog, we learned about Polymorphism in Java using Overloading and Overriding. We explored:
- Method Overloading, which occurs at compile-time and enables multiple methods with the same name but different parameters.
- Method Overriding, which allows runtime polymorphism by enabling a subclass to modify the behavior of a superclass method.
- How both concepts together enable flexible and dynamic method execution.
Polymorphism is a crucial concept in Java programming, making code more maintainable, scalable, and reusable. Understanding these concepts will help you write better object-oriented programs.