Difference between Method/Function Overloading and Overriding (Polymorphism)

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?

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:

  1. Method Overloading (Compile-Time Polymorphism)
  2. 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 three add 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 generic drive 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 and PayPal classes implement the Payment interface.
  • By using the Payment reference, the program dynamically decides the payment method, showcasing polymorphism in action.

Differences Between Method Overloading and Method Overriding

AspectMethod OverloadingMethod Overriding
PurposeTo define multiple methods with the same name but different parameters.To provide a specific implementation in a subclass for a superclass method.
BindingCompile-timeRun-time
ScopeWithin the same classAcross a superclass-subclass hierarchy
Return TypeCan differMust 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

  1. Favor Interfaces: Use interfaces to define generic behaviors, allowing multiple implementations and promoting extensibility.
  2. Choose Clear Method Names: For overloaded methods, make parameter types and method purposes clear to avoid confusion.
  3. Use @Override Annotation: This helps ensure methods are correctly overridden and improves code readability.
  4. 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.

76 thoughts on “Difference between Method/Function Overloading and Overriding (Polymorphism)

  1. Have you ever thought about adding a little bit more than just your articles? I mean, what you say is valuable and everything. Nevertheless think about if you added some great pictures or video clips to give your posts more, http://www.kayswell.com“pop”! Your content is excellent but with pics and videos, this site could certainly be one of the best in its niche. Terrific blog!

  2. You’re so interesting! I don’t suppose I have read something like this before. So nice to discover another person with a few genuine thoughts on this subject. Seriously.. many thanks for starting this up. This web site is something that’s needed on the web, someone with a little originality! http://www.kayswell.com

  3. First off I would like to say superb blog! I had a quick question which I’d like to ask if you don’t mind. I was interested to find out how you center yourself and clear your thoughts before writing. http://www.kayswell.com I have had a difficult time clearing my mind in getting my ideas out there.I truly do take pleasure in writing but it just seems like the first 10 to 15 minutes are

  4. Wonderful goods from you, man. I’ve understand your stuff previous to and you’re just too excellent.I really like what you have acquired here, certainly likewhat you are stating and the way in which you say it.You make it entertaining and you still care for to keep it wise.I cant wait to read much more from you. http://www.kayswell.com This is actually a wonderful site.

  5. Thanks for revealing your ideas here. The other element is that when a problem comes up with a laptop motherboard, folks should not consider the risk associated with repairing the item themselves for if it is not done properly it can lead to permanent damage to all the laptop. It’s usually safe just to approach your dealer of a laptop for any repair of the motherboard. They’ve technicians with an competence in dealing with notebook computer motherboard issues and can have the right diagnosis and execute repairs.

  6. You really make it appear really easy together with your presentation however I in finding this topic to be actually something that I believe I might by no means understand. It sort of feels too complicated and very extensive for me. I’m looking forward on your subsequent submit, I will attempt to get the hang of it!

  7. I was just looking for this info for a while. After 6 hours of continuous Googleing, finally I got it in your web site. I wonder what is the lack of Google strategy that don’t rank this kind of informative web sites in top of the list. Normally the top websites are full of garbage.

  8. I have been exploring for a little bit for any high-quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this web site. Reading this information So i抦 happy to convey that I have a very good uncanny feeling I discovered just what I needed. I most certainly will make sure to don抰 forget this site and give it a look regularly.

Leave a Reply

Your email address will not be published. Required fields are marked *