Method Overloading in Java

Method Overloading takes place when a class has many methods with the same name but different parameters. If we only need to do one operation, having the methods named the same improves the program’s readability. If you define the method as a(int, int) for two parameters and b(int, int, int) for three parameters, it may be difficult for you and other programmers to grasp the behavior. As a result, we use overloading to figure out the program quickly.

What is the purpose of method overloading?

Assume you have to execute the addition of provided numbers, but there might be any number of arguments (for simplicity, let’s consider two or three).

Create two methods, sum2num(int, int) and sum3num(int, int, int), for two and three parameters, respectively, to complete the work. Other programmers, as well as you in the future, maybe puzzled because the action of both methods is identical, but their names are different.

Overloading methods are a better way to accomplish this task. As a result, one of the overloaded methods is then called, depending on the argument given. The latter contributes to the program’s readability.

What is the benefit of method overloading in Java?

Method overloading has several advantages. Some of these include:

  • We don’t have to develop new names for functions that do the same thing. If Java did not offer to overload, we would have to generate method names like sum1, sum2,… or sum2Int, sum3Int,… etc., in our code.
  • The readability of the program is improved by method overloading.
  • It gives programmers more freedom because they can use the same approach for different sorts of data.
  • Overloading gives the code a neat appearance.
  • The execution time is reduced because the binding is done during the compilation process.
  • Overloading methods reduce the code’s complexity.
  • It allows us to reuse the code, which saves memory.

How does the Java compiler distinguish between overloaded methods?

The Java compiler uses the signatures of overloaded methods to distinguish them. A method’s signature comprises its name and a list of parameters. The method signature does not include the return type of the method. It has no bearing on resolving overloaded methods.

When a class contains numerous methods with the same name but different parameter lists, the compiler distinguishes between them by looking at the number of parameters or the types of parameters supplied. As a result, utilize method overloading with caution because the java compiler does not consider the return type when differentiating overloaded methods.

Which (Java compiler or JVM) decides the overloaded method to call?

Because methods are called using objects, only the JVM selects which overloaded method is to be executed at runtime (dynamically). The JVM handles the construction of an object at runtime. As a result, the JVM determines which overloaded method is called at runtime. At the time of compilation, the Java compiler does not decide which of the overloaded methods is called by the user.

How does the JVM know which of the overloaded methods is being called?

When several methods with the same name are defined in a class, JVM looks at the signature of the methods. The name of the method and its parameters make up the method signature.

The signatures of two methods with the same name will almost certainly differ. Two people with the same name, for example, will almost certainly have different signatures. JVM recognizes that the two methods are distinct based on their signatures and determines which method should be invoked.

Method Overloading Characteristics

The following are some of the features of Method overloading in Java that you should be aware of.

  • The call to the overloaded method is bonded at compilation time.
  • In Java, method overloading is often referred to as compile-time polymorphism.
  • Overloading methods are usually done in the same class. However, we can do it in the subclass as well. You must use the extends keyword to create a relationship between the parent and child classes.
  • In Java, method overloading cannot be accomplished by modifying the method’s return type because this may generate ambiguity. On the other hand, overloaded methods can change the return type.
  • In Java, we can overload private methods.
  • In Java, the final methods can be overloaded.
  • In Java, the primary method can likewise be overloaded.
  • In Java, both static and instance methods can be overloaded. When two or more static methods have the same name but differ in the list of parameters, method overloading is possible.

When should you utilize the Java method of overloading?

Although method overloading is a valuable feature of Java, you should only utilize it when necessary. It should be used when numerous methods with distinct arguments are required, but they perform the same task. Do not use the method overloading idea if numerous methods perform different duties. In Java, method overloading is used to meet the following requirements:

  • To reuse the same method name, method overloading is used.
  • It is done to improve the program’s logical readability and comprehension.
  • It is used in Java to achieve compile-time polymorphism.

Overloading can be done in several ways.

  • Altering the number of arguments
  • The data type can be changed.
  • The sequence of the Data type of parameters used

Method Overloading is not feasible in Java by simply modifying the method’s return type.

method overloading: Changing the number of arguments in a method

In this example, we’ve built two methods: the first sumValues() function adds two integers, while the second add() method adds three numbers. We’re constructing static methods in this example so that we don’t have to generate instances when invoking methods.

class Calculation{  
  static int sumValues(int a,int b){return a+b;}  
  static int sumValues(int a,int b,int c){return a+b+c;}  
}  
class OverloadingTestClass{  
  public static void main(String[] args){  
    System.out.println(Calculation.sumValues (14,52));  
    System.out.println(Calculation.sumValues (09,32, 45));  
  }
}  

Overloading a method: modifying the data type 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 given to the second add method.

class Calculation{  
  static int sumValues(int a, int b){return a+b;}  
  static double sumValues(double a, double b){return a+b;}  
}  
class TestOverloading2{  
  public static void main(String[] args){  
    System.out.println(Calculation .sumValues (33,61));  
    System.out.println(Calculation .sumValues (67.55,48.65));  
  }
}  

Method Overloading: The sequence of the Data type of parameters

For example:

sumValues(int, float)
  
sumValues(float, int)

The function dispValues() is overloaded based on the sequence of data types of parameters – the sequence of data types in the argument list is different in both methods. The first technique uses a(char, int) argument list, while the second approach uses a (char, int) argument list (int, char). The method can be overloaded without issue because the sequence is different.

class OverloadingClass
{
   public void dispValues(char c, int num)
   {
       System.out.println("I'm the first definition of method disp");
   }
   public void dispValues(int num, char c)
   {
       System.out.println("I'm the second definition of method disp" );
   }
}
class OverloadingTestClass
{
   public static void main(String args[])
   {
       OverloadingClass overloadClass = new OverloadingClass();
       overloadClass.dispValues ('x', 21 );
       overloadClass.dispValues (62, 'y');
   }
}

Type Promotion and Method Overloading

One type is implicitly promoted to another if no matching datatype is identified. Let’s look at an illustration to understand the concept better. A byte can be promoted to short, int, long, float, or double. The int, long, float, or double datatypes can all be promoted from the short datatype. The char datatype can be promoted to other data types such as int, long, float, and double. TypePromotion is an example of method overloading.

class Calculation{  
  void sumValues(int a,long b){System.out.println(a+b);}  
  void sumValues(int a,int b,int c){System.out.println(a+b+c);}  

  public static void main(String args[]){  
    Calculation calcObj=new Calculation();  
    calcObj.sumValues (45,40);//now second int literal will be promoted to long  
    calcObj.sumValues (45,40,45);  

  }  
}  

Example: Method Overloading with Type Promotion if matching found

Type promotion is not applied if the method has matching type arguments.

class Calculation{  
  void sumValues(int a,int b){System.out.println("int arg method invoked");}  
  void sumValues(long a,long b){System.out.println("long arg method invoked");}  

  public static void main(String args[]){  
    Calculation obj=new Calculation();  
    obj.sumValues (45,45);//now int arg sum() method gets invoked  
  }  
}  

Example: Method Overloading with Type Promotion in case of ambiguity

In the event of ambiguity, an example of Method overloading with type promotion. There will be ambiguity if the method has no matching type arguments, and each method promotes a comparable amount of parameters.

class Calculation{  
  void sumValues(int a,long b){System.out.println("a method invoked");}  
  void sumValues(long a,int b){System.out.println("b method invoked");}  

  public static void main(String args[]){  
    Calculation calc=new Calculation();  
    calc.sumValues(45,45);//now ambiguity  
  }  
}  

Frequently Asked Questions

The following are the frequent questions on Method Overloading.

Is it possible to overload the main() function in Java?

Method overloading, to be precise. Method overloading allows you to have any number of main methods in a class. However, JVM invokes the main() function, which only accepts a string array as an argument. Let’s take a look at a simple example:

class OverloadingTestClass{  
  public static void main(String[] args){System.out.println("main with String[]");}  
  public static void main(String args){System.out.println("main with String");}  
  public static void main(){System.out.println("main without args");}  
}  

Example: A Java program with an overloaded main()

import java.io.*;

public class OverloadClass {

	// Normal main()
	public static void main(String[] args)
	{
		System.out.println("Hi Code (from main)");
		OverloadClass.main("Code");
	}

	// Overloaded main methods
	public static void main(String arg1)
	{
		System.out.println("Hi, " + arg1);
		OverloadClass.main("Dear Code", "My Code");
	}
	public static void main(String arg1, String arg2)
	{
		System.out.println("Hi, " + arg1 + ", " + arg2);
	}
}

Why isn’t method overloading available only by modifying the method’s return type?

Because of ambiguity, method overloading in Java is not achievable by modifying the method’s return type. Let’s look at some examples of ambiguity:

class Calculation{  
  static int sumValues(int a,int b){return a+b;}  
  static double sumValues(int a,int b){return a+b;}  
}  
class OverloadingTestClass{  
  public static void main(String[] args){  
    System.out.println(Calculation.sumValues (45,45));//ambiguity  
  }
}  


System.out.println(Calculation.sumValues(45,45)); // How does Java know which sumValues() method to use in this case?

Compile Time Error is preferable to Run Time Error. If you declare the same method with the same parameters, the java compiler generates an error.

Is it possible to overload static methods?

‘Yes,’ is the answer. Two or more static methods with the same name but different input parameters are possible. Take, for example, the Java application below. For more information, see this.

// filename Test.java
public class OverloadClass {

	public static void showInfo() {
		System.out.println("Test.foo() called ");
	}
	public static void showInfo(int a) {
		System.out.println("OverloadClass.showInfo (int) called ");
	}
	public static void main(String args[])
	{
		OverloadClass.showInfo ();
		OverloadClass.showInfo (10);
	}
}

Is it possible to overload methods that only differ by the static keyword?

In Java, we can’t overload two methods that only differ by the static keyword (the number of parameters and types of parameters are the same). For example, look at the Java application below. For more information, see this.

// filename Test.java
public class OverloadClass {

	public static void showInfo() {
		System.out.println("OverloadClass.showInfo () called ");
	}
	public void showInfo() { // Compiler Error: cannot redefine showInfo()
		System.out.println("OverloadClass.showInfo (int) called ");
	}
	public static void main(String args[]) {
		OverloadClass.showInfo ();
	}
}

Is Operator Overloading supported in Java?

Java does not support user-defined overloaded operators, unlike C++. Java overloads operators internally; for example, the + operator is overloaded for concatenation.

Overloading vs Overriding: What’s the Difference?

Overloading refers to the use of various signatures for the same function. On the other hand, Overriding is when two or more classes share the same function and signature but are linked through inheritance.

Example 1: Overloading – Parameter data types differ

Method disp() is overloaded in this example based on the data type of parameters – we have two methods with the name disp(), one with a char type parameter and the other with an int type parameter.

class OverloadingClass
{
    public void dispValues(char c)
    {
        System.out.println(c);
    }
    public void dispValues(int c)
    {
       System.out.println(c );
    }
}

class OverloadingTestClass
{
    public static void main(String args[])
    {
        OverloadingClass overloadClass = new OverloadingClass();
        overloadClass.dispValues ('a');
        overloadClass.dispValues (5);
    }
}

Example 2: Overloading – Different Number of Parameters in Argument List

This example demonstrates how method overloading is accomplished by varying the number of parameters.

class OverloadingClass
{
    public void dispValues(char c)
    {
         System.out.println(c);
    }
    public void dispValues(char c, int num)  
    {
         System.out.println(c + " "+num);
    }
}
class OverloadingTestClass
{
   public static void main(String args[])
   {
       OverloadingClass overloadClass = new OverloadingClass();
       overloadClass.dispValues ('a');
       overloadClass.dispValues('a',10);
   }
}

Example 3: Method Overloading and Type Promotion

class OverloadingClass{

   void dispValues(int a, double b){
	System.out.println("Approach I");
   }
  
   void dispValues(int a, double b, double c){
	System.out.println("Approach II");	
   }
  
   public static void main(String args[]){
	OverloadingClass overloadClass = new OverloadingClass();
	/*
	* I'm sending a float value as a second argument,
	* but it was promoted to the type double because
	* no method had an arg list like (int, float)
	*/

	overloadClass.dispValues (350, 55.75f);
   }
}

Example: Real-World example of method overloading

class CodeHelperService {

    private String formatNumber(int value) {
        return String.format("%d", value);
    }

    private String formatNumber(double value) {
        return String.format("%.3f", value);
    }

    private String formatNumber(String value) {
        return String.format("%.2f", Double.parseDouble(value));
    }

    public static void main(String[] args) {
        CodeHelperService codeService = new CodeHelperService();
        System.out.println(codeService .formatNumber(324));
        System.out.println(codeService .formatNumber(78.9934));
        System.out.println(codeService .formatNumber("128"));
    }
}

Conclusion

Method overloading is a feature that allows a class to have multiple methods with the same name but different argument lists. It’s analogous to Java’s constructor overloading, which lets a class have many constructors with various argument lists.

Let’s come back to the point: when we say argument list, we refer to a method’s parameters. That is to say, the argument list of a method sumValues(int a, int b) with two arguments differs from the argument list of a method sumValues(int a, int b, int c) with three parameters.

If we merely modify the return type of methods, it is not method overloading. Differences in the number of parameters must exist.

Some things to keep in mind when it comes to method overloading include changing the return type of methods does not allow for method overloading. Also, the most fundamental rule of method overloading is that the arguments of two overloaded methods must differ.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *