Java is a powerful language that is based on the ideas of object-oriented programming. Code written in object-oriented programming like Java is modular, reusable, versatile, and debug-friendly due to its many capabilities. Java’s powerful feature of method overloading enables a single method to carry out multiple tasks depending on the parameters it receives. This improves the readability and maintainability of our code in addition to increasing its versatility.
In this article, we will cover the key concept of method overloading in Java. We will cover the concept in-depth with their rules, and different ways to perform method overloading in Java. Along with this, we will see examples of each way used to perform the overloading. The article will also cover some other key concepts including the difference between method overriding with method overloading.
Understanding Polymorphism in Java
Let us first look into what method overloading is in Java, but before that let’s delve into the basic idea of Polymorphism, which is essential for understanding it. The term Polymorphism originates from two Greek words – “poly” meaning many and “morph” meaning shape. At the core of object-oriented programming lies this concept of polymorphism. It refers to the ability of an object to take many forms, wherein a single entity can present itself in multiple ways.
The term polymorphism in Java when applied to an object means that this object can act as if it were a member of its parent class instead of a member of its class. This is very beneficial for writing reusable code because more flexibility allows for the same operation to behave differently for different classes. In Java, we use method overloading (also known as compile-time polymorphism) and method overriding (also known as runtime polymorphism) to achieve polymorphism.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
What is Method Overloading in Java?
Method Overloading is a way to achieve polymorphism in Java, where it allows a class to have more than one method with the same name and distinct parameters. This is referred to as polymorphism at compile time. During compilation, the method signature determines which method is appropriate. Java’s method overloading feature allows a single method to perform various functions based on the parameters it takes— an enhancement that boosts your code’s readability and maintainability while also amplifying its flexibility. This improves the readability and maintainability of your code in addition to increasing its versatility. When two or more methods in the same class have the same name but different argument lists (different types, numbers, or both), this is known as method overloading.
Method overloading is known by different names such as Early binding, Static polymorphism, or compile-time polymorphism. If you hear any word around you, always use method overloading.
Features of Method Overloading:
Method overloading is a type of compile time polymorphism, meaning the methods are bound at the compile time instead of run-time.
It is a static binding approach in Java.
The actual method overloading is determined by the kind, sequence, and number of arguments.
It is referred to as function overloading in other programming languages.
Constructor overloading and method overloading are comparable in Java. The main difference is that constructor overloading only affects the class’s constructor methods, whereas method overloading affects the methods that are declared within the class.
Java method overloading results in overloaded methods with distinct parameter lists.
Rules of Method Overloading
To achieve method overloading in Java, some specific rules must be followed:
Method names must be the same.
The methods must be in the same class or same subclass.
Methods must have different parameter lists. For example, different numbers of parameters, different types of parameters, or different order of parameters.
Different Ways to Do Method Overloading in Java
Method overloading can be achieved in Java using three different ways. Here are some of the ways through which we can do method overloading.
Changing the Number of Parameters.
The simplest way to achieve method overloading in Java is to change the number of parameters of a method. Here, we mean to increase or decrease the number of method parameters. For example, if we have a method sumAddOfNumbers(int x, int y) with initially as two parameters, then to overload this method, we can use the same method name but with an increased number of parameters. Java makes it easy to identify between methods when there is a difference in the number of parameters.
Like, for adding 3 numbers, we can make this method as sumAddOfNumbers(int x, int y, int z). Similarly, for 4 numbers, we can have our method as sumAddOfNumbers(int x, int y, int z, int a), etc.
Example:
public class SumExample {
// Method with 2 parameters
int sumOfNumbers(int number1, int number2) {
// Return the sum of numbers
return number1 + number2;
}
// Overloaded method with 3 parameters
int sumOfNumbers(int number1, int number2, int number3) {
// Return the sum of numbers
return number1 + number2 + number3;
}
// Overloaded method with 4 parameters
int sumOfNumbers(int number1, int number2, int number3, int number4) {
// Return the sum of numbers
return number1 + number2 + number3 + number4;
}
// Overloaded method with 5 parameters
int sumOfNumbers(int number1, int number2, int number3, int number4, int number5) {
// Return the sum of numbers
return number1 + number2 + number3 + number4 + number5;
}
public static void main(String[] args) {
//creating the object for the SumExample class
SumExample object = new SumExample();
// printing the values of the sum for all overloaded methods
System.out.println("The result of the numbers is: " + object.sumOfNumbers(30, 40));
System.out.println("The result of the numbers is: " + object.sumOfNumbers(30, 40, 50));
System.out.println("The result of the numbers is: " + object.sumOfNumbers(30, 40, 50, 60));
System.out.println("The result of the numbers is: " + object.sumOfNumbers(30, 40, 50, 60, 70));
}
}
Output:
The result of the numbers is: 70
The result of the numbers is: 120
The result of the numbers is: 180
The result of the numbers is: 250
Explanation:
In the given example, we have overloaded a method sumOfNumbers() with a different number of parameters. Initially, we defined only two parameter numbers, then overloaded the same method with the same name but with a larger number of parameters. Finally, in the main method, we have created an object for the class and accessed the methods to print the result of the numbers based on the input parameters.
Changing Data Types of the Arguments.
Another way to achieve method overloading in Java is to change the data types of parameters or arguments in a method. Here, we mean to change the type of data that a method is accepting. For example, if we have a method sumAddOfNumbers(int x, int y) with initially integer type of parameters, then to overload this method, we can use the same method name but with different types of parameters like double, float, complex, etc. Java makes it easy to identify between methods when there is a difference in the data types of parameters.
Note: When you change the data type of the parameters or the arguments, you also need to change the method return type to the same as of parameters you are using. Like, using Int parameters must be returned by the Int return type, similarly for other data types.
For example, to overload the method sumAddOfNumbers(int x, int y, int z) from int to double, we can overload it as sumAddOfNumbers(double x, double), etc.
Example:
public class SumExample {
// Method with int data type
int sumOfNumbers(int val1, int val2) {
// Return the sum of numbers
return val1 + val2;
}
// Method with double data type
double sumOfNumbers(double val1, double val2) {
// Return the sum of numbers
return val1 + val2;
}
// Method with float data type
float sumOfNumbers(float val1, float val2) {
// Return the sum of numbers
return val1 + val2;
}
public static void main(String[] args) {
//creating the object for the SumExample class
SumExample object = new SumExample();
// printing the values of the sum for all overloaded methods
System.out.println("The result of the numbers is: " + object.sumOfNumbers(30, 40));
System.out.println("The result of the numbers is: " + object.sumOfNumbers(456.13, 556.4));
System.out.println("The result of the numbers is: " + object.sumOfNumbers(40.4f, 50.4f));
}
}
Output:
The result of the numbers is: 70
The result of the numbers is: 1012.53
The result of the numbers is: 90.8
Explanation:
In the given example, we have overloaded a method sumOfNumbers() with different data types in the parameters. Initially, we defined the int parameters with int as the return type, then overloaded the same method twice with the same name but with double and float as parameters and return type. Finally, in the main method, we have created an object for the class and accessed the methods to print the result of the numbers based on the input parameters.
Changing the Order of the Parameters of Methods
We can also achieve method overloading in Java by changing the order of the parameters or arguments in a method. This method is useful when there are different types of parameters. Java can identify if the method is overloaded or not just by checking the order of the parameters or the arguments.
For example, to overload the method having parameters as (int n1, double n2), we can write it also as (double n1, int n2). After changing the order, if both the methods have the same name, then both these methods are considered to be overloaded with different sequences of parameters.
Example:
class SumExample {
// Method with int and double data type parameters
void checkType(int n1, double n2) {
// Display the numbers
System.out.println("The int type value is: " + n1 + ", The double type value is: " + n2);
}
// Overloaded Method with double and int data type parameters
void checkType(double n1, int n2) {
// Display the numbers
System.out.println("The double type value is: " + n1 + ", The int type value is: " + n2);
}
// Overloaded Method with int and String data type parameters
void checkType(int n1, String n2) {
System.out.println("The int type value is: " + n1 + ", The string type value is: " + n2);
}
// Overloaded Method with String and int data type parameters
void checkType(String n1, int n2) {
System.out.println("The string type value is: " + n1 + ", The int type value is: " + n2);
}
public static void main(String[] args) {
//creating the object for the SumExample class
SumExample object = new SumExample();
// printing the values of all overloaded methods
object.checkType(10, 30.5);
object.checkType(30.5, 10);
object.checkType(30, "Hello herovide");
object.checkType("Hello herovide", 10);
}
}
Output:
The int type value is: 10, The double type value is: 30.5
The double type value is: 30.5, The int type value is: 10
The int type value is: 30, The string type value is: Hello herovide
The string type value is: Hello herovide, The int type value is: 10
Explanation:
In the given example, we have overloaded a method checkType() with different parameter types and orders. Here, each method prints the parameter values, showcasing how Java can differentiate between methods with the same name but different signatures. Finally, in the main method, we have created an object or instance of the SumExample class and called each overloaded method to display the results.
Method Overloading with Type Promotion
The method can also be overloaded with type promotion in Java. In this approach, If there is no matching data type, one type is implicitly promoted to another. When necessary, Java can automatically promote one type of data to another. When the precise parameter type is unavailable, this can be helpful in cases of method overloading.
But here there may be a situation when the exact prototype does not match with arguments. So, in that case, the compiler works on the priority of the data types. In this concept, the lower-size data type can be converted to the high-size data type. See the below diagram for more details about the priority:
Let’s see a detailed example of how we can convert a low-size data type to a high-size data type in Java using the type promotion concept.
Example:
class MyExample {
// Method with int data type parameters
void checkType(int val) {
// Display the number
System.out.println("The int type value is: " + val);
}
// Overloaded Method with double data type parameters
void checkType(double val) {
// Display the number
System.out.println("The double type value is: " + val);
}
public static void main(String[] args) {
//creating the object for the MyExample class
MyExample object = new MyExample();
// printing the values of all overloaded methods
objects.checkType(10);
object.checkType(30.5);
object.checkType('B'); // char type promoted to int
object.checkType('G'); // char type promoted to int
}
}
Output:
The int type value is: 10
The double type value is: 30.5
The int type value is: 66
The int type value is: 71
Explanation:
In this example, we are type-promoting the method checkType() with different parameter types: one for int and another for double. Every method outputs the parameter’s value. To demonstrate Java’s type promotion, we have created an object or instance of the MyExample class and called all overloaded methods, including ones that cause char values to be automatically promoted to int.
Method Overloading vs. Method Overriding
In Java programming, people get confused between two terms: Method Overloading and Method Overriding. They both are the concepts of polymorphism in Java. Though they are used in different settings and have different rules and behaviours, both approaches allow the same method name to be used for diverse purposes.
Method Overloading
When a class contains several methods with the same name but different arguments, this is known as method overloading. It is a compile-time polymorphism approach in which the method signature i.e., method name and argument list, determines the method to be performed at compile time.
Example:
public class Example {
// Creating a sum method with two variables
int performSub(int val1, int val2) {
return val1 + val2;
}
// Overloading a sum method with three variables
int performSub(int val1, int val2, int val3) {
return val1 + val2 + val3;
}
// Overloading a sum method with different data type arguments
double performSub(double val1, double val2) {
return val1 + val2;
}
// Main method
public static void main(String[] args) {
// Creating object of class
Example obj = new Example();
int res1 = obj.performSub(301, 401);
int res2 = obj.performSub(301, 401, 601);
double res3 = obj.performSub(60.3, 30.4);
// Printing results
System.out.println("The result for the sum is: " + res1);
System.out.println("The result for the sum is: " + res2);
System.out.println("The result for the sum is: " + res3);
}
}
Output:
The result for the sum is: 702
The result for the sum is: 1303
The result for the sum is: 90.69999999999999
Method Overriding
When a subclass offers a particular implementation of a method that is already specified in its superclass, this is known as method overriding. It is a runtime polymorphism approach in which the actual type of the object is used to determine at runtime which method should be used.
Example:
// Parent class
class Vehicle {
// Method in the superclass
void feature() {
String a = "Vehicle runs on road";
System.out.println(a);
}
}
// Extended class to override
class Car extends Vehicle {
// Overridden method in the subclass
@Override
void feature() {
String a = "Car has less mileage than Bike!";
System.out.println(a);
}
}
// Extended class to override
class Bike extends Vehicle {
// Overridden method in the subclass
@Override
void feature() {
String a = "Bike has more mileage than Car!";
System.out.println(a);
}
}
// Main method
public class Example {
public static void main(String[] args) {
// Creating objects of class
Vehicle myVehicle = new Vehicle();
Vehicle myCar = new Car();
Vehicle myBike = new Bike();
// Accessing the object's methods
myVehicle.feature();
myCar.feature();
myBike.feature();
}
}
Output:
Vehicle runs on road
Car has less mileage than Bike!
Bike has more mileage than Car!
Difference Between Method Overloading and Method Overriding
It is used to overload a method of the same name but with a different number of parameters, and types of parameters.
It is used to override or redefine the method in a subclass that is already defined in a parent class.
Polymorphism
Method overloading is a type of compile-time polymorphism.
Method overriding is a type of run-time polymorphism.
Return type
The return type can be the same or different.
The return type of method overriding must be of the same type else you will get a runtime error.
Arguments
Here the arguments can be of different types, numbers, or both.
Here the arguments must be the same.
Access modifier
The method overloading can have different access modifiers.
The method overriding can have a more restrictive access modifier in Java.
Exception handling
This can throw different types of exceptions related to which type of parameters it’s using.
It can throw errors related to the subclass only.
Inheritance
Here, inheritance is not used as we are creating different methods with the same name but different parameters.
Here, inheritance is a must to define the relationship between the child class and the parent class.
Method resolution
It is resolved at compile-time.
It is resolved at run-time.
Code reusability
There is more code reusability as same-name methods are being reused.
There is less code reusability compared to overloading.
Use case
It is used to make related activities have the same method name, which increases readability and reusability.
It is used to give particular implementation information for a method that is already defined in a superclass in a subclass.
Maintainability
Code is maintainable in method overloading also.
Automatic is reflected in child classes once the changes are made.
Benefits of Method Overloading
Better Readability and Maintainability: By enabling the use of the same method name for comparable capabilities, method overloading enhances the readability of the code, and clean code practices make it easier for new developers to grasp.
More Adaptability: Method overloading gives you the ability to handle different data types, different numbers of arguments, or varied amounts of parameters by enabling multiple methods with the same name.
Improved Reusability of Code: Code reuse is encouraged by overloaded methods in Java with less code. A single method name can contain several input types instead of requiring the creation of different methods for each set of parameters, which reduces redundancy and simplifies code organisation.
Polymorphism: Compile-time polymorphism, often known as static polymorphism or early binding, is a type of method overloading. It makes it possible for the same method to carry out many tasks depending on various parameters, strengthening the object-oriented nature of
Constructors: In Java, method overloading can also be used on the constructors for creating different objects by passing different data.
Common Mistakes in Method Overloading
Code can become complex and difficult to maintain if there are too many methods overloading each other with slight variations in parameters. It could be difficult for developers to discern between overloaded methods, which could result in mistakes.
Another common mistake is changing the method return type only for overloading, which is a bad practice. Not only must the return types of overloading methods vary, but also their parameter lists. An error occurs during compile time if the return type is the only thing changed in the method.
Compile-time errors may result from overloading methods with similar argument lists, which could result in unclear method calls. This is known as ambiguous calls in Java. This occurs when the inputs supplied to the compiler are insufficient to decide which method to invoke.
Overusing Varargs (variable arguments) in overloaded methods can occasionally result in unclear or unexpected behaviour. Therefore, the varargs need to be utilised carefully to prevent the overuse.
Combining the concepts of method overriding inside the method overloading.
Best Practices for Method Overloading
The use of overloaded methods is recommended to carry out tasks that are similar or related. This will make the code logical and easy to understand; however, avoid overloading methods that perform different operations as it can lead to confusion among API users.
Ensure consistency in naming conventions for overloaded methods. This indicates their relationship and promotes the readability of the code, facilitating comprehension for other developers working on the project.
The development of overloaded methods should show very clearly that their parameter types and counts differ significantly. This helps in avoiding any ambiguity and deciding which method to call becomes straightforward.
Overloading should enhance flexibility but be careful not to create too many methods with the same purpose.
Designing overloaded methods must also consider the types and order of parameters in such a way that it gives rise to clear and intuitive signatures.
Conclusion
The method overloading feature allows the programmers to specify several methods with the same name but different parameters. For better results in readability, efficient maintenance, and code reuse, programmers use the concept of method overloading in Java. In this article, we have learned about method overloading in Java. We have covered the foundational concept of method overload known as polymorphism, its types, and working.
We have also covered the different ways to do method overloading including the type promotion, along with this we have seen the important rules for method overloading. You can successfully include method overloading into your Java programs by adhering to the rules and best practices described in this article.
FAQs
Is method overloading the same as function overloading?
The idea of method overloading and function overloading is the same. They just belong to different contexts. For Java, we use the term "method" because Java is an object-oriented programming language where functions are defined within classes and called methods. In Java, method overloading allows the definition of multiple methods with the same name but different parameters (type, number, or both) within the same class.
Can we overload static methods?
Yes, static methods are overloadable in Java just like instance methods. Overloading of static methods involves having several static methods bearing identical names but distinct parameter lists within a single class - this facilitates alternative method implementations according to varying inputs.
Does Java support Method Overriding?
Yes, Java does allow method overriding. It is when a subclass offers its implementation of a method that already exists in the superclass- thus enabling the subclass to alter or enhance the behaviour of the superclass method.
Does Java use the concept of Operator Overloading?
No, operator overloading is not supported by Java. Operator overloading is used in languages like C++ which enables several interpretations of the same operator depending on the operand types and the context.
What is the difference between method overloading and overriding?
In Java, there are two different concepts: overloading and overriding of methods. Within a single class, method overloading refers to the creation of numerous methods with the same name but distinct parameters. This type of polymorphism occurs during compilation. On the other hand, method overriding takes place when a subclass provides a particular implementation of a method that is already defined in the superclass. This kind of polymorphism occurs during runtime.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.