Method overloading vs overriding in java

There are numerous contrasts between technique Method overloading and Method overriding in java. A rundown of contrasts between technique method overloading and method overriding are given underneath:

 

Method Overloading Method Overriding
It represents compile time polymorphism. It represents run time polymorphism.
Method overloading provides a way to increase the readability of the program. Method overriding provides specific implementation of the method in the child class that is already provided by it’s parent class.
Method overloading is performed inside the class. Method overriding occurs in two classes that have association of IS-A relationship type.
Parameter must be different. Parameter must be same.
In java, technique method-overloading can’t be performed by only changing the return type of the method. Return type can be same or distinctive in method-overloading. Parameter change is must. In case of method overriding, return type of method must be same or covariant.

 

Example: Method Overloading

class SubtractionTest {
 
    public void subtraction(int num1, int num2) {
        System.out.println(num1 - num2);
    }
 
    public void subtraction(int num1, int num2, int num3) {
        System.out.println(num1 - num2 - num3);
    }
 
 }
 
public class Main
{
	public static void main(String[] args) {
		SubtractionTest subtractionTest = new SubtractionTest();
		subtractionTest.subtraction(150, 100);
		subtractionTest.subtraction(150, 100, 20);
	}
}

Output

50
30

Example: Method Overriding

class SubtractionTest {
 
    public void subtraction(int num1, int num2) {
        System.out.println("Inside super class method");
        System.out.println(num1 - num2);
    }
 
 }
 
public class Main extends SubtractionTest
{
 
    public void subtraction(int num1, int num2) {
        System.out.println("Inside sub class method");
        System.out.println(num1 - num2);
    }
 
	public static void main(String[] args) {
		Main main = new Main();
		main.subtraction(150, 100);
	}
}

Output

Inside sub class method                                     
50

Java interview questions on method overloading and overriding

Please follow and like us:
Content Protection by DMCA.com