Difference between Method/Function Overloading and Overriding (Polymorphism)
Polymorphism, a foundational concept in object-oriented programming (OOP), allows methods or functions to process objects differently based on their data type or class. In Java, polymorphism enables one interface to be used for a general class of actions, allowing a program to behave dynamically depending on the context. This tutorial explains polymorphism, covers its types and benefits, and illustrates its implementation in Java.
What is Polymorphism?
Contents
- What is Polymorphism?
- 1. Compile-Time Polymorphism (Method Overloading)
- Example of Method Overloading
- 2. Run-time polymorphism (Method Overriding)
- Example of Method Overriding
- Upcasting and Dynamic Method Dispatch
- Benefits of Polymorphism
- Real-World Example: A Payment System
- Differences Between Method Overloading and Method Overriding
- Polymorphism in Interfaces
- Best Practices for Using Polymorphism in Java
- Summary
- Share this:
- Like this:
- Related
Polymorphism, from Greek words meaning “many forms,” refers to the ability of an object to take on multiple forms. It allows a single function or method to work differently based on the object calling it, which enhances code flexibility and reusability. In Java, polymorphism can be achieved through:
- Method Overloading (Compile-Time Polymorphism)
- Method Overriding (Run-Time Polymorphism)
1. Compile-Time Polymorphism (Method Overloading)
In function overloading, multiple methods in the same class have the same name but different parameter lists. The compiler determines which method to call based on the method signature. This decision is made during compilation, hence the term “compile-time polymorphism.”
Example of Method Overloading
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double values
double add(double a, double b) {
return a + b;
}
}
public class TestCalculator {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println("Add two integers: " + calculator.add(5, 10));
System.out.println("Add three integers: " + calculator.add(5, 10, 15));
System.out.println("Add two doubles: " + calculator.add(5.5, 10.5));
}
}
In this example:
- The
Calculator
class defines threeadd
methods with different parameters. - The compiler selects the correct method based on the argument type and number, providing flexibility without altering method names.
2. Run-time polymorphism (Method Overriding)
In method overriding, a subclass provides a specific implementation of a method that is already defined in its superclass. This type of polymorphism is resolved during runtime. Run-time polymorphism supports the concept of “one interface, many methods” by allowing different subclasses to provide their unique implementations of a superclass method.
Example of Method Overriding
class Car {
void drive() {
System.out.println("The car is driving.");
}
}
class Sedan extends Car {
@Override
void drive() {
System.out.println("The Sedan run smoothly on the highway.");
}
}
class SUV extends Car {
@Override
void drive() {
System.out.println("The SUV run smoothly on the highway.");
}
}
class SportsCar extends Car {
@Override
void drive() {
System.out.println("The SportsCar zooms at high speed on the track.");
}
}
public class CarTest {
public static void main(String[] args) {
Car mySedan = new Sedan();
Car mySUV = new SUV();
Car mySportsCar = new SportsCar();
mySedan.drive();
mySUV.drive();
mySportsCar.drive();
}
}
In this example:
- The
Car
superclass provides a genericdrive
method. Each subclass (Sedan, SUV, and SportsCar) overrides drive with its unique behaviour. Using a Car reference for different car types enables polymorphic behaviour at runtime through dynamic method dispatch.
Upcasting and Dynamic Method Dispatch
Java uses upcasting to handle method calls at runtime. When a superclass reference points to a subclass object, it can call overridden methods in the subclass based on the object’s actual type. This process is known as dynamic method dispatch and is a key feature of runtime polymorphism.
Car Suv = new Car(); // Upcasting
Suv.drive(); // Calls drive method due to dynamic method dispatch
Benefits of Polymorphism
Code Reusability: Reusable code is a major advantage of polymorphism. Methods with the same name can work with different types or classes, reducing code redundancy.
Extensibility: New classes and methods can be added with minimal changes to existing code, as polymorphic behavior is inherently adaptable.
Maintainability: A polymorphic approach improves code organization, making the codebase easier to manage and maintain.
Real-World Example: A Payment System
Consider a payment system with different payment methods like CreditCard and PayPal. Polymorphism allows creating a general Payment
interface that can handle different payment methods dynamically.
interface Payment {
void makePayment(double amount);
}
class CreditCard implements Payment {
@Override
public void makePayment(double amount) {
System.out.println("Paid " + amount + " with Credit Card.");
}
}
class PayPal implements Payment {
@Override
public void makePayment(double amount) {
System.out.println("Paid " + amount + " via PayPal.");
}
}
public class PaymentSystem {
public static void main(String[] args) {
Payment payment1 = new CreditCard();
Payment payment2 = new PayPal();
payment1.makePayment(100.00);
payment2.makePayment(250.00);
}
}
In this system:
- Both
CreditCard
andPayPal
classes implement thePayment
interface. - By using the
Payment
reference, the program dynamically decides the payment method, showcasing polymorphism in action.
Differences Between Method Overloading and Method Overriding
Aspect | Method Overloading | Method Overriding |
---|---|---|
Purpose | To define multiple methods with the same name but different parameters. | To provide a specific implementation in a subclass for a superclass method. |
Binding | Compile-time | Run-time |
Scope | Within the same class | Across a superclass-subclass hierarchy |
Return Type | Can differ | Must be the same or covariant |
Polymorphism in Interfaces
Java interfaces support polymorphism by allowing a class to implement multiple interfaces. This approach can lead to flexible and extensible designs.
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a Circle");
}
}
class Square implements Drawable {
public void draw() {
System.out.println("Drawing a Square");
}
}
public class ShapeTest {
public static void main(String[] args) {
Drawable shape1 = new Circle();
Drawable shape2 = new Square();
shape1.draw(); // Outputs "Drawing a Circle"
shape2.draw(); // Outputs "Drawing a Square"
}
}
Best Practices for Using Polymorphism in Java
- Favor Interfaces: Use interfaces to define generic behaviors, allowing multiple implementations and promoting extensibility.
- Choose Clear Method Names: For overloaded methods, make parameter types and method purposes clear to avoid confusion.
- Use
@Override
Annotation: This helps ensure methods are correctly overridden and improves code readability. - Keep Methods Specific to Purpose: Avoid excessive method overloading that could reduce code clarity.
Visit the detailed presentation.
Summary
Polymorphism in Java is a robust tool for creating flexible, reusable, and maintainable code. By supporting both compile-time (method overloading) and run-time (method overriding) polymorphism, Java allows methods to adapt based on context, empowering developers to create more dynamic applications.
This detailed tutorial follows your comprehensive guide’s structure by focusing on real-world examples, in-depth explanations, and coding illustrations.
3 thoughts on “Difference between Method/Function Overloading and Overriding (Polymorphism)”
kırmadan dökmeden su kaçak tespiti Su kaçağı sorunumu çözdüler, artık içim rahat. https://frenzay.com/ustaelektrikci
apreciariam o seu conteúdo. Por favor, me avise.
Esta página tem definitivamente toda a informação que eu queria sobre este assunto e não sabia a quem perguntar. Este é o meu primeiro comentário aqui, então eu só queria dar um rápido