Table of Content
- Introduction
- How does Overloading Work in Java?
- Examples of Method Overloading in Java
- Types of Overloading in Java
- Rules for Overloading in Java
- Features of Method Overloading
- Advantages of Method Overloading
Introduction to Overloading in Java
Java is an Object-Oriented programming language, and it follows basic OOPs concepts. Overloading is one of the important concepts in Java. Overloading allows different methods having the same name in a class but with different signatures. Signature includes the number of parameters, the data type of parameters and the sequence of parameters passed in the method. In Java, the method and the constructors both can be overloaded.
The process of method overloading occurs at compile-time, earning it the designation of compile-time polymorphism. Programmers engage in method overloading within a class to enhance program readability, allowing for the creation of improved implementations of a method tailored to various scenarios.
Consider a scenario in which the programmer wants to find out the volume of various geometric figures like the cube, cylinder, and rectangular prism as three of them have a different formula for finding the volume and have a different number of parameters. The volume of the cube will need only one parameter, the cylinder will take two, and the rectangular prism will take three parameters. But the main purpose is to find the volume of figures only. So we can create separate methods of volume for different figures but with the same name. In this way, Method Overloading is used in practical scenarios.
Syntax:
class Demo
{
void addition(int val ,int val)
{
}
void addition(float val, float val, float val)
{
}
void addition(double val, double val)
{
}
}
There are two possible ways to overload:
- Changing the number of arguments.
- Changing the data types.
Consider the above code snippet; class Demo contains an overloaded addition() method with an int return type and change in a number of arguments.
How does Overloading Work in Java?
Working of Method Overloading is explained with an example:
Code:
class Main{
int volume(int side)
{
return side * side * side;
}
int volume(int length, int breadth, int height)
{
return length*breadth*height;
}
double volume(int radius, int height)
{ return 3.14 * (radius * radius)* height / 3;
}
public static void main(String[] args)
{
Main oe = new Main();
System.out.println("Volume of Cube " +oe.volume(10));
System.out.println("Volume of Rectangular prism " +oe.volume(10,12,30));
System.out.println("Volume of Cone "+oe.volume(5,10));
} }
Output:
Explanation of the above code: In the above example, we need to find the volume of 3 geometric figures, so we have created 3 separate overloaded methods with the same name as ‘volume’, but all the methods have different numbers of arguments.In the main method, executing one.volume(10) invokes the method volume with a single parameter (i.e., int volume(int side)). Different methods are called and processed based on the number of arguments for other volume methods.
In this example, the overloading of methods occurs not only based on the number of arguments but also based on the data type of parameters and the sequence of parameters. Consequently, the program calls these methods according to these criteria.
Examples of Method Overloading in Java
Given below are the examples of method overloading in java:
Example #1
Consider the following example for overloading by changing a number of arguments.
Code:
import java.util.*;
class Demo2
{
int addition(int a,int b)
{
int res;
res=a+b;
return res;
}
int addition(int a,int b,int c)
{
int res;
res=a+b+c;
return res;
}
int addition(int c)
{
int res;
res=c+1;
return res;
}
}
public class OverloadingDemo
{
public static void main(String[] args)
{
Demo2 obj=new Demo2();
System.out.println("Method Overloading Demo");
Scanner scr=new Scanner(System.in);
System.out.println("Enter Three Integer values for a,b,c:");
int a=scr.nextInt();
int b=scr.nextInt();
int c=scr.nextInt();
System.out.println("Addition Method with two parameters:"+obj.addition(a, b));
System.out.println("Addition Method with Three Parameters:"+obj.addition(a, b, c));
System.out.println("Addition Method with one parameter:"+a+"+1:"+obj.addition(a));
}
}
Output:
The above example program declared three addition() methods in a Demo2 class. All three methods overload with different parameters; the first method takes three integer-type parameters and returns an integer value. The second overloaded addition() takes two integer values, calculates addition, and returns the result of an integer type value.
Example #2
Program for overloading by changing data types and return types.
Code:
import java.util.*;
class Demo3
{
float addition(int a,float b)
{
float res;
res=a+b;
return res;
}
float addition(float a,float b,float c)
{
float res;
res=a+b+c;
return res;
}
double addition(double a,double b)
{
double res;
res=a+b;
return res;
}
}
public class OverloadingDemo1
{
public static void main(String[] args)
{
System.out.println();
Demo3 obj=new Demo3();
Scanner scr=new Scanner(System.in);
System.out.println("Enter one Integer and floating point number:");
int a=scr.nextInt();
float b=scr.nextFloat();
System.out.println("Calling addition method with addition(int,float)"+obj.addition(a, b));
System.out.println("Enter three Floating point numbers:");
float i=scr.nextFloat();
float j=scr.nextFloat();
float k=scr.nextFloat();
System.out.println("Calling addition(float,float,float)"+obj.addition(i, j, k));
System.out.println("Enter two double type numbers:");
double x=scr.nextDouble();
double y=scr.nextDouble();
System.out.println("Calling addition(double,double):"+obj.addition(x, y));
}
}
Output:
The above example program demonstrates overloading methods by changing data types and return types. We declare three additional methods with differences in the type of parameters and return types. The first method takes two parameters of type int and floats to perform addition and return a float value. The second overloaded method takes three floating-point parameters to perform addition and returns a float value. And the third overloaded method takes two double values and returns a double value.
Example #3
Program to calculate the area of Square, Rectangle, and circle by overloading area() method.
Code:
import java.util.*;
class ComputeArea
{
void area(double r)
{
double area;
area=142*r*r;
System.out.println("Area of Circle for radius:"+r+":"+area+" SQ units");
}
void area(float side)
{
double res;
res=Math.pow(side,2);
System.out.println("Area of Square="+res+" Sq units");
}
void area(float len,float wid)
{
double res=len*wid;
System.out.println("Area of Rectangle (Len X Wid):"+res+" Sq units’");
}
}
public class AreaDemo
{
public static void main(String[] args)
{
Scanner scr=new Scanner(System.in);
ComputeArea obj=new ComputeArea();
System.out.println("Please Enter radius value to calculate area of circle");
double r=scr.nextDouble();
obj.area(r);
System.out.println("Please Enter side value to calculate area of square");
float x=scr.nextFloat();
obj.area(x);
System.out.println("Enter Length and width of rectangle:");
float l=scr.nextFloat();
float w=scr.nextFloat();
obj.area(l, w);
}
}
Output:
Types of Overloading in Java
There are basically 3 ways of Method Overloading in Java:
1. Number of Parameters
Java methods can be overloaded by the number of parameters passed in the method. For example, if the 1 method of volume has 2 parameters and another method has 3 parameters, then it comes under Overloading on the basis of the number of parameters.
Code:
class Multiplication
{
int mult(int a,int b) // method mult having 2 parameters
{
return a*b;
}
//Method Overloading on number of parameters
int mult(int a,int b,int c) // method mult having 3 parameters
{
return a*b*c;
}
}
class Main
{
public static void main(String[] args)
{
Multiplication M = new Multiplication();
System.out.println(M.mult(10,9));
System.out.println(M.mult(10,9,8));
}
}
Output:
2. Datatype of Parameters
The datatype of parameters passed in the method matters a lot, and hence methods can be considered as Overloaded if 2 or methods have the same name having the same or the different number of arguments but different data types of parameters in the different methods.
Code:
class Multiplication
{
int mult(int a,int b) // method mult having 2 parameters
{
return a*b;
}
//Method Overloading on datatype of parameters
double mult(double a,double b) // method mult overloaded
{
return a*b;
}
}
class Main
{
public static void main(String[] args)
{
Multiplication M = new Multiplication();
System.out.println(M.mult(10,9));
System.out.println(M.mult(10.5,9.8));
}
}
Output:
3. Sequence of Parameters
Changing the sequence of parameters for two or more overloaded methods can enable method overloading.
For example, if we have one method with parameters (String x, char y) and another method with parameters (char x, String y), both sharing the same name, we consider these two methods to be overloaded due to a distinct sequence of parameters.
Code:
class Employee
{
void details(String name, char rank) // method details having 2 parameters
{
System.out.println("Employee name is "+name);
System.out.println("Employee ranking is "+rank);
} //Method Overloading on sequence of parameters
void details(char rank, String name) // method details overloaded
{
System.out.println("Employee name is "+name);
System.out.println("Employee ranking is "+rank);
}
}
class Main
{
public static void main(String[] args)
{ Employee emp = new Employee();
emp.details("Rajesh", 'A'); // calls the first method (details(String, char))
emp.details("Ram", 'B'); // calls the second method (details(char, String))
}
}
Output:
In the provided code example, both methods within the ‘details’ function achieve overloading based on the sequence of parameters. Executing the statement emp.details(‘Rajesh’, ‘A’) invokes and processes the method with the parameters arranged in the order (String, char), namely void details(String name, char rank).
Rules for Overloading in Java
Below are the rules that should be remembered in java overloading:
- The first and foremost rule of Method overloading is that Methods need to have the same name in a single class.
- Two or more methods in a class can undergo overloading based on distinct signatures. The signature encompasses the number of parameters, data types of parameters, and the sequence of parameters, as explained above.
- The return type of a method does not constitute a part of the signature. Attempting to perform overloading based on the return type is not allowed, and the compiler generates an error in such cases.
Features of Method Overloading
Listed below are the features:
- Since the method overloading is static polymorphism, i.e., methods are bound during the compilation process.
- Overloading affects the runtime; methods bind at compile-time, eliminating the need for binding or checking processes during runtime.
- Only changing the return of the method does not consider method overloading. This results in an ambiguity error.
- The number of arguments, order of arguments, and type of arguments are part of the actual method overloading.
Advantages of Method Overloading
Listed below are the advantages:
- The reduction in execution time occurs because the binding takes place during compilation time.
- An overloading mechanism achieves flexibility.
- Code reusability is achieved; hence it saves memory.
- Code complexity is reduced. Hence provides consistency of code.
Conclusion
Overloading stands out as a crucial concept in Java applicable to both methods and constructors. Before implementing overloading in programming, it’s essential to adhere to certain rules.
Recommended Articles
We hope that this EDUCBA information on “Overloading in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information.