Table of Contents

Java Overloading and Overriding Methods

Overloading Methods:

A class that has multiple methods having the same name but different in parameters, is known as Method Overloading.  Method overloading is used when objects are required to perform similar tasks but using different input parameters.

Why method overloading is used?

Method overloading increases the readability of the program. Overloaded methods give programmers the flexibility to call a similar method for different types of data.

There are two ways to overload the method in java

  1. By changing number of arguments
  2. By changing the data type

1. By changing number of arguments :

In this example, there are two methods with the same name ( add( ) ) but have different parameters. Hence by changing the number of arguments methods can be overloaded.

class MethodOverloading {
   static int add(int x, int y) {
       return x + y;
   }
   static double add(double x, double y) {
       return x + y;
   }
}
class Test {
   public static void main(String[] args) {
       System.out.println(Adder.add(2, 3));
       System.out.println(Adder.add(15.5, 10.9));
   }
}
/*OUTPUT:
5
26.4 */
Overriding Methods:

When the base class ( subclass ) and derived class ( parent class ) have the same method names, then it is called method overriding. If the subclass provides a specific definition of a parent class method, then this action is Method Overloading.

Why method overriding is used?

The primary use of method overriding is that the child class can have a different implementation of a parent class method without even changing the definition of the parent class method.

Rules for Java Method Overriding

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. There must be an IS-A relationship (inheritance).

Example:

import java.lang.*;
class Father {
   //defining a method  
   void work() {
       System.out.println("Father is working in an office");
   }
}
//Creating a child class  
class Son extends Father {
   //defining the same method as in the parent class  
   void work() {
       System.out.println("Son is working sums");
   }

   public static void main(String args[]) {
       Son s = new Son(); //creating object  
       s.work(); //calling method  
   }
}
/*OUTPUT:
Son is working sums */

Difference between Method Overloading and Method Overriding

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?