Method Overloading vs Method Overriding in Java

In this tutorial, you will learn the difference between Method Overloading and Method Overriding in Java. Let’s have a look at a little comparison side by side. 

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.

Method Overloading Example

The below code snippet is an example of Method Overloading in Java. We can have several methods with the same name in one class, but the parameters must be different.

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

Method Overriding Example

The below code snippet is an example of Method Overriding in Java. In the Blue class, we override the method printColour from the parent class Colour.

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");
  }
}

I hope this tutorial was helpful to you. To learn more, check out the Java Tutorials for Beginners page. 

 

Leave a Reply

Your email address will not be published.