i

JAVA Complete Course

Overriding and Overloading of methods

 

overloading-vs-overriding

Overloading and Overriding are two very important concepts of Java. They are confusing for beginner Java programmers. This post illustrates their differences based on simple examples.

Let’s simply go with definitions. Overloading is when two or more methods in the same class have the same name but different parameters.

Overriding means having two methods with the same name and parameters (i.e., method signature). One of the methods belongs to parent class and another to child class. Overriding allows a child class to provide its specific implementation of a method that is already provided in its parent class.

The important things about overriding and overloading are that:

  • Overriding is taking place at run-time and actual object (not reference type) determines which overridden method should be called.
  • Polymorphism applies to overriding, not to overloading.
  • Overloading takes place during compile time and object reference type defines which overloaded method should be called.
  • Overriding happens at run-time while overloading takes place during compile time.

Example of overriding:

Output will be: bowl

Example of overriding:

 

Method overloading

Method overriding

The usage of method overloading is to increase the readability of the program.

Method overriding is used in order to provide the specific implementation of the method which is already defined in its super class.

Method overloading is done within class.

Method overriding happens in two classes that have IS-A (inheritance) relationship.

During method overloading, parameter must be different.

During method overriding, parameter must be same.

Method overloading is the case of compile time polymorphism.

Method overriding is the case of run time polymorphism.

In java, method overloading can't be performed if we change only return type of the method. In the overloaded method return type can be same or different. But we must have to change the parameter.

In method overriding return type must be same or covariant