Java fundamentals – Overloading Vs Overriding

4 min read

Hey Guys! In this post, we will be learning paradigm within OOPS polymorphism known as overloading and overriding.

In simple words, Polymorphism means the ability of a object to attain multiple physical forms. For example, a car can be of petrol, diesel, Automatic or EV variant.

What is method overloading?

Overloading is a feature by which more than one methods in a class can have same name with different digital signatures. Digital signature only includes arguments, not the return type.

Rules of Overloading

  1. Methods must have same name.
  2. Methods must be in same class.
  3. Methods must have different type of arguments.
  4. Access modifiers are not part of overloading.
  5. Checked/Unchecked exception are not part of overloading.
  6. Return types are not part of overloading.

Below is the example of how to achieve overloading

public class SampleOverloading {
    public void printData(){}
    public void printData(String data){}
    public void printData(int data){}
    public void printData(float data){}
}

Overloading is also called as compile-time polymorphism as the method resolution is done at compile time. Overloading follows static binding, that means method resolution will based on the type of reference Object.

What is method overriding?

A child class can inherit properties and methods from parent class after extending it. These inherited method is called as derived methods. Base class may want to alter functionality of some derived methods. That altering of inherited methods is called overriding.

Rules of Overriding

  1. Derived methods must have same name.
  2. Derived methods must have same arguments.
  3. Derived methods can have covariant or same return type.
  4. Derived methods must not have stricter access restrictions.
  5. Derived methods must not have broader scope of checked exceptions.
  6. Occurs in IS-A relationship or parent-child relationship.

Below is an exhaustive example for overriding.

class Car {
    public void prettyPrint() {
        System.out.println("Hey! This is parent car");
    }
}
class Audi extends Car {

    @Override
    public void prettyPrint() {
        System.out.println("Hey! This is audi car");
    }
}
public class SampleOverriding {
    public static void main(String[] args) {
        Car car = new Car();
        car.prettyPrint(); //Hey! This is parent car
        
        Car audi = new Audi();
        audi.prettyPrint(); //Hey! This is audi car
    }
}

Overriding is also called as Runtime Polymorphism as the method resolution is done at runtime. Overriding follows dynamic binding as the resolution is dependent on the type of object created rather than type of reference(in case of overloading).

Mostly, the interview questions are asked from rules of overriding and overloading or from the concepts of binding/method resolution.

Hope this article will be helpful.

Happy Learning!!