Overloading vs Overriding

Photo by Amy Chen on Unsplash

Overloading vs Overriding

Mirror Images with Hidden Differences

Overload - The Power of Versatility

We can use the same method name, but the method parameter should differ by the number of parameters or type of parameter

Okay! What is the use of that right?

Using the same method name for a similar kind of operation makes it easy to understand the code as well as utilize the OOPS. So the same method performs different tasks based on the parameter.

Consider a scenario where you need to add two numbers, here The numbers sometimes comes as integer other time double. How you can utilize the Overload concept here,

public class Calculator {
    // method name add, parameter is integer
    public int add(int a, int b) {
        return a + b;
    }
   // // method name add, parameter is double
    public double add(double a, double b) {
        return a + b;
    }
}

Override - The Art of Refinement

An override allows the subclass to give a different implementation for the same method available in the parent class.

In the programming world, it is very common that you will end up in situation where you need to customize the output without disturbing the parent functionality.

So the best fit is to go for an override, Look at the below example of how the draw method gives different implementations,

class Shape {
    // Other common props
    //.
    //.
    // common draw method for shape
    void draw() {
        System.out.println("Drawing a shape");
    }
}

class Circle extends Shape {
    // sub class overrides and gives specific implementaion
    @Override
    void draw() {
        System.out.println("Drawing a circle");
    }
}

Conclusion:

Indeed both overload and override important concepts in the OOPS world. Overload allows you to create methods with the same name but different parameters, while Override enables you to customize inherited methods in subclasses. By combining these concepts, both helps to create a powerful and elegant software solution.


"Your likes are a simple click but mean the world to me. Thank you for your support!"