Overloading in Java

What is Overloading in Java?

Method Overloading in Java is when a class contains many methods with the same name but different argument lists.

Overloading invokes a method based on the arguments when a class includes two or more methods with the same name but distinct parameters. Compile-time polymorphism and overloading are connected

 

Overloading in Java

Overloading In Brief

If the quantity and/or type of parameters differ, multiple methods can share the same name. Therefore, Method Overloading Can be done by two ways:

  1. Method Overloading with the use of various argument data types.

  2. Overloading a method by increasing the number of arguments.

Now let’s have a look at the code snippets-

Overloading In Java Diagram

Overloading by Increasing Arguments

Here, we have a method name sum which is overloaded by increasing the number of arguments as the parameters in the method.

Run
public class Main {

	public int sum(int x, int y)
	{
		return (x + y);
	}

	public int sum(int x, int y, int z)
	{
		return (x + y + z);
	}

	public static void main(String args[])
	{
		Main s = new Main();
		System.out.println(s.sum(20,10));
		System.out.println(s.sum(16, 78, 4));
        }
}

Overloading by Increasing Arguments

Here, we have a method name sum which is overloaded by changing the parameter’s variable type arguments in the method.

Run
public class Main {

	public int sum(int x, int y)
	{
		return (x + y);
	}

	public double sum(double x, double y)
	{
		return (x + y);
	}

	public static void main(String args[])
	{
		Main s = new Main();
		System.out.println(s.sum(20,10));
		System.out.println(s.sum(63.97, 21.053));
        }
}

Advantages of Overloading:

  • For functions that perform the same function, we don’t need to come up with and keep track of many names. For instance, in our code, we would have to write method names like sum1, sum2,… or sum2Int, sum3Int,… etc. if overloading was not enabled by Java.
  • The idea behind dynamic code (method) binding is called method overriding. In other words, based on the object we use to invoke the function, the runtime decision as to whether the method will bind or execute is made.
  • For each overloaded method, a return type needs to be specified. Numerous return kinds are possible for methods.
  • Java’s runtime engine does not view changing a method’s return type alone as method overloading. Therefore, methods must have different signatures and return types.
  • During compilation, the binding is completed, which reduces execution time.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription