Difference between Method Overloading and Method Overriding
Key Differences
Method Overloading Method Overriding
Method Overloading always happens within the same class.Method Overriding always happen between a super class and a sub class.
In method overloading the return type of the method need not to be the same.In method overriding the return type of the method must be same 
Number of arguments can be different.Number of arguments should be same.
Overloaded methods can have different access specifiers.Overriding method should not have weaker access specifier than the method it is overriding.
Type of arguments can be same or different.Type of arguments should be same.
In method overloading one method cannot hide the other method.In method overriding base class method hides the super class method.
It helps to achieve Static or Compile time PolymorphismIt helps to achieve Dynamic or Run time Polymorphism

The above picture tries to show the difference between Overloading and Overriding.

  • In overloading we have more than one arrow(method) and they are all available at runtime.
  • In overriding we may have more than one arrow, but at runtime we have only one arrow that is available.
  • In overloading their return type or parameters or type of parameters can be different.
  • In overloading their return type, parameters and type of parameters all must be same.

Examples of Overloading and Overriding
Try to identify Overloading and Overriding in the example given below.

class Base {
  public void print() {
     System.out.println("Base class print()");   
class Derived extends Base {

  public String show(String args) {
     return "";  
  public void show() {
     System.out.println("No args show");     
  public void print() {
     System.out.println("Derived class print()");   
  public static void main(String[] args) {
      Derived obj = new Derived();
      obj.show("String overloaded show");
Output of the program is
No args show
String overloaded show
Derived class print()

In this example the method show() is overloaded and the method print()  is overridden. Thus it is clear that we can access all the overloaded methods, but only one overridden method( method in the super class is hidden).

No comments :

Post a Comment