Difference Between Overloading and Overriding

This difference always a big question in developers minds. Even I do get confused sometimes and I believe this explanation and best practice will help you through the understanding the differences of those methods

Overloading:

in the same class n methods using the same names but acquiring different parameters/arguments. Let’s see them in an example:

public class MethodOverloadingExample {

    public void doTask(){ 
    }

    public void doTask(int jobID){
    }

    public void doTask(int jobID, String jobName){
    } 
}

As you can see, I have defined 3 void functions having the same names with having different arguments. You can create n amount of functions this way, also this is possible in subclasses as well.

Overriding:

This occurs when a subclass has the same function as superclass does. Let’s evaluate the example below:

public class Animal {
    public void move(){
        System.out.println("Move");
    }
}

public class Dog extends Animal{
    public void move(){
        System.out.println("Move");
    }
}

public class Cat extends Animal{
    public void move(){
        System.out.println("Move");
    }
}

As you can see Dog and Cat classes extends to the animal class and have the same void methods as the others do. By doing this, JVM in runtime overriding the functions and enabling you to use those functions

Leave a Reply

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