Difference between method overloading and method overriding in Java

Share

Method:  It is a set of statements that collectively perform a specific task and can be invoked any number of times by using its name. In other words, these lines of code are grouped together to form a method and this defined method can be used any number of time. It reduces the length of the code and improves readability.

Polymorphism: It refers to ability to take multiple forms. In Java, method overloading and overriding are the ways to implement polymorphism.

Method Overloading

Overloading is a feature that allows a class to have multiple methods having same name. In order to achieve this, one can change number of method arguments or argument datatypes.

Syntax:

class A {
void show () {
// body
}

// overloading 

void show (int x) {

// body
}
...

}

 

Method Overriding

Overriding is a feature that allows a subclass to have a method that is already defined in parent class, with same name and signature, but different implementation.

Syntax:

class A {
void show () {
// body
}
}

class B extends A {

// overriding

@override
void show () {

// body
}
...

}

 

Difference between method overloading and overriding in Java in tabular form

[wpsm_comparison_table id=”22″ class=”center-table-align”]

 

Java Overriding Example:

public class PUBG {

    void demageAWM (){

        System.out.println("1 shot damage 100 % ");
    }

}

class PUBGUpdatedVersion extends PUBG {
// overriding demageAWM()
    @Override
    void demageAWM() {
        System.out.println("1 shot damage 95%");
    }
}

class test {

    public static void main(String[] args) {
        PUBGUpdatedVersion gun = new PUBGUpdatedVersion();
        gun.demageAWM();
    }
}

Output:

1 shot damage 95%

Java Overloading Example

public class PUBG {
// overloading attachments()
    void attachments (String scope){

        System.out.println("This is pistal with "+scope);
    }

    void attachments (String scope, String mag,String extender){

        System.out.println("This is Auto Gun with "+scope+","+mag+", "+extender);
    }

}


class test {

    public static void main(String[] args) {
        PUBG gun = new PUBG();
        gun.attachments("Red dot");
        gun.attachments("6x","AWM mag","AWM extender");
    }
}

Output:

This is pistal with Red dot
This is Auto Gun with 6x,AWM mag, AWM extender

This post was last modified on July 4, 2022

Sandeep Verma

Published by
Sandeep Verma
Tags: Difference java method overloading method overriding