Method Overloading vs Method Overriding in Java

 

Method Overloading Method Overriding
Overloading happens at compile-time.
It is an example of compile-time polymorphism.
Method overriding is an example of run-time polymorphism.
Overloading is being done in the same class. For overriding, superclass and subclass are required
Static binding is being used for the overloaded method Dynamic binding is being used for overridden/overriding methods.
In the case of method overloading, the method parameters must be different. In the case of method overriding, the method parameters must be the same.
The return type of method does not matter in case of method overloading. It can be the same or different. The return type must be the same or covariant in method overriding.

Example of Method Overloading:

class Car {
    
  public void start() {
    // ...
  }
    
  public void start(int a) {
    // ...
  }
    
  public void start(String str) {
    // ...
  }
}


In one class, we can have several methods with the same name, but the parameters must be different.

Example of Method Overriding:

class Colour {
  
  public void printColour()
    System.out.println("This is general colour");
  }
}
 
class Blue extends Colour {
  
  public void printColour()
    System.out.println("This is blue colour");
  }
}

In the Blue class, we override the method printColour from the parent class Colour.

That’s it!

 

Leave a Reply

Your email address will not be published.