Method Overloading in Java2 min read

Introduction

Method Overloading in java occurs when a class has many methods with the same name but distinct parameters. If we only need to conduct one operation, having the methods named the same improves the readability of the program.

  • In Java, it is possible to define two or more methods with the same name within the same class, as long as, their parameter declarations are different. Through method overloading, Java implements polymorphism i.e “one interface, multiple methods”.
  • Method overloading is used when objects are required to perform conceptually similar tasks using different input parameters.
  • The return type of method is insufficient to distinguish the two methods, and hence, overloaded methods must differ in the type and/or a number of their parameters. When an overloaded function is called Java executes the version of the method whose parameters match the arguments.
  • We say that the name of the method is overload because it has several different meanings Java doesn’t get the methods mixed up but can tell which one you want to call by the number and types of the actual parameters that you prove in the method call statement.

Why you should use Method Overloading

  • Overloading the method increases the program’s readability. This gives programmers the flexibility to use the same method for various data types.
  • The code looks clean, therefore. This reduces the runtime because the binding takes place in the compilation time.
  • The overloading method minimizes code complexity.
  • This enables us to use the code that saves memory again.
Different ways to perform method overloading in java

Different ways to perform method overloading

  1. Method Overloading by changing no. of arguments
  2. Method Overloading by changing datatype of arguments

Method Overloading by changing no. of arguments

In this example, we’ve built two methods: the first add() function adds two integers, while the second add() method adds three numbers.

class Adder{  
	static int add(int a, int b){
    	return a + b;
    }  
	static int add(int a, int b, int c){
    	return a + b + c;
    }  
}

public class TestOverloading1{  
	public static void main(String[] args){  
		System.out.println(Adder.add(11,11));  
		System.out.println(Adder.add(11,11,11));  
	}
}  

Output :

22
33

Method Overloading by changing datatype of arguments

We’ve generated two methods in this example, each with a different data type. Two integer arguments are passed to the first add method, and two double arguments are passed to the second add method.

class Adder{  
	static int add(int a, int b){
    	return a + b;
    }  
	static double add(double a, double b){
    	return a + b;
    }  
}  

public class TestOverloading2{  
	public static void main(String[] args){  
		System.out.println(Adder.add(11,11));  
		System.out.println(Adder.add(12.3,12.6));  
	}
}  

Output :

22
24.9

Share:

Leave a Reply