Overloading vs Overriding in Java

Here we will be discussing only the differences between method overloading and method overriding. Visit either of the topics below to learn about them in detail.

Method OverloadingMethod Overriding
It occurrs within a class.It occurs among classes that have IS-A (inheritance) relationship.
Parameters must be different either in number or type.Parameters must be same both in number and type.
This is the primary way to achieve compile time polymorphism in Java.This is the primary way to achieve run-time polymorphism.
Method overloading cannot occur by changing the return type only.
(Java doesn't support return type based method overloading.)
Return type of the overriding method must be the same as the overridden method or a subtype atleast.
So overriding allows you to change the return types a little i.e return types may be narrower.
private, final and static methods can be overloaded.
Even constructors can be overloaded.
private, final and static methods cannot be overridden.
Even constructors cannot be overridden.
Overloaded methods may have different access modifiers.Access modifiers of the overriding methods must not be more restrictive.
Methods may throw different ExceptionsOverriding method must not throw newer or broader checked exceptions.
They can only throw narrower checked Exceptions and any unchecked Exceptions

1. A Visual Representation

Method overloading and method overriding are the primary way to achieve polymorphism in Java. Overloading happens within a class while overriding happens among classes that have IS-A (inheritance) relationship.

 

Overloading vs Overriding in Java
Method Overloading vs Method Overriding in Java. Overriding is used in context of inheritance.

 


2.1 Example : Method Overloading

Let’s convert the method overloading diagram above into an example. There is a box class and it has two overloaded methods. Depending on whether the Box is a cube or a cuboid, the corresponding method is called.

Output :

Depending on the number of the arguments, the relevant method is called.


2.2 Example : Method Overriding

Let’s convert the method overriding diagram above into an example. There is a Employee class which has a method called getSalary() which returns the salary for given number of months. This class is subclassed by Engineer class and the method is overridden to return more salary than an average employee.

Output :

Depending on whether the Employee is an Engineer or a regular Employee the relevent method is called at the runtime.