Differences between Overriding and Overloading in Java?

Overloading occurs when two or more methods in one class have the same method name but different parameters (i.e., method signature).

Overriding means having two methods with the same method name and parameters (i.e., method signature). One of the methods is in the parent class and the other is in the child class.

  1. The real object type in the run-time, not the reference variable’s type, determines which overridden method is used at run-time. In contrast, reference type determines which overloaded method will be used at compile time.
  2. Polymorphism applies to overriding, not to overloading.
  3. Overriding is a run-time concept while overloading is a compile-time concept.

 

Method Overloading Method Overriding
Method Overloading occurs with in the same class Method Overriding occurs between two classes super-class and subclass
Since it involves with only one class inheritance is not involved. Since method overriding occurs between super-class and subclass inheritance is involved.
In overloading return type need not be the same In overriding return type must be same.
Parameters must be different when we do overloading Parameters must be same.
Static polymorphism can be achieved using method overloading Dynamic polymorphism can be achieved using method overriding.
In overloading one method can’t hide the another In overriding subclass method hides that of the superclass method.

 

Example of Overriding:-

Output:-

In the example above, the vehicle variable is declared to be a vehicle. During compile time, the compiler checks if the vehicle class has the enginestart() method. As long as the vehicle class has the enginestart() method, the code compilers. At run-time, a Car is created and assigned to vehicle. The JVM knows that vehicle is referring to the object of Car, so it calls the enginestart() method of Car. This is called Dynamic Polymorphism.

 

Example of Overloading:-

Output:-