Difference between method Overloading and method Overriding in Java

Difference between method Overloading and method Overriding in Java


The following are the main differences between method overloading and method overriding in java programming language:

Method Overloading Method Overriding
In Java programming language, method overloading is used to increase the readability of the program. In java programming language the method overriding is used to provide a specific implementation of the method whose implementation has already been done in its parent class or super class.
In java or other programming languages the method overloading is done within a class. In Java programming language method overriding is occurred in two classes and these have IS- A relationship. Also called inheritance.
Parameters should be different when performing method overloading in java programming language. Parameters should be same in method overriding.
We can achieve compile time polymorphism by using method overloading. We can achieve run time polymorphism by using method overloading.
In java programming language the method overloading is achieved by changing the parameters of the methods or functions and not the name or return type of the methods or functions. Return type of the methods however can be the same or different in method overloading. But parameters must be changed. The return type of the methods must be same in order to perform method overriding.


Java method overloading example:

Consider the following example in which we have implemented method overloading:

CODE:

class ExampleOverloading {

static int add (int x, int y) {

return x + y;

}

static int add (int x, int y, int z) {

return x + y + z;

}

}

It can be seen in the above code that the parameters of the methods are different and hence we achieved method overloading and it is done within one class only.


Java method overriding example:

class Animal {

void display () {

system. out. println (“Animals that are mammals”);

}

}

class Cat extends Animal {

void display () {

system. out. println (“Cats are mammals”);

}

}

It can be seen in the above example that there are two classes which has same methods. The name and parameters of the methods are same and hence we performed method overriding successfully. Each method of the class will be called by using its object.