Method Overloading and Overriding: Functions and Differences

The question, “What is the difference between overloading and overriding?” is by far the most frequently requested interview question for Java developers. Before we get into the answer, let’s first get a better understanding of the subject by going over some straightforward examples of method overloading and method overriding.

Overloading and Overriding

What is Method Overloading?

The same method name and different parameters, or the number, type, or order of the parameters, must be used when overloading a method (method signature).

Note: Return type is not part of the method signature. Hence, changing return type with two methods having same method name and parameters will result in compile time error.

Example of Method Overloading:

Method Overloading
Method Overloading

What is Method Overriding?

A child class may provide its own implementation of a method provided in the parent class by using the OOP feature known as method overriding, sometimes referred to as function overriding or run-time polymorphism. The method in the child class must have the same name, signature, and return type as the method in the base class in order for the implementation to take precedence over the definition.

Example of Method Overriding:

Method overriding
Method overriding

Key Difference

  • Objective. Method Overloading is employed to make the programme easier to read. To provide the precise implementation of the method, method overriding is employed. The super class method is overridden by the child class.
  • The quantity of classes included. Overloading of methods is done in class. There is only one class at issue. In method overriding, two classes with an IS-A connection are involved (inheritance). In other words, method overriding requires a parent class and a child class.
  • Parameters. Parameters for method overloading must be distinct. Method overriding requires same parameters, i.e., method signatures (although parameters can be different for covariant return type).
  • Type of polymorphism. A compile-type polymorphism example is method overloading. Run-type polymorphism includes, for example, method overriding.
  • Return type. The method’s return type has no bearing on method overloading. When a method is overload, the return type may be the same or different. A different parameter is required. The same return type or a covariant return type must be used when overriding a method.
  • Private, static or final method : You can not override private, static or final method in java. But you can overload  private, static or final methods in java.