The meaning of overloading is serving one or more functions with a similar name. Java provides the ability to overload methods. Method overloading is a single class that can have multiple methods with a similar name, but they should be distinct in a signature or the number of parameters and return type of the method. This method of overloading functionality advantages codes readability and reusability of the program.
Method Overloading lets different methods have a similar name but distinct signatures where the signature can be distinct by the number of input parameters or type of input parameters or a combination of both. Method overloading is also called Compile-time Polymorphism, Static Polymorphism, or Early binding in Java. Method overloading in comparison to the parent argument, the child argument will get the most elevated significance.
Here is an example of how method overloading works in Java
// Java program to demonstrate working of method
// overloading in Java
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum(). This sum takes two double
// parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
OUTPUT:
30
60
31.0
Our Learners Also Read: What is an Array in Java?
In Java, we can overload constructors like methods. Constructor overloading can be described as the concept of holding more than one constructor with distinct parameters so that each constructor can complete a different assignment. Here, we require to comprehend the objective of constructor overloading. Sometimes, we require to use multiple constructors to initialize the other values of the class.
We must also see that the java compiler summons a default constructor when we do not operate any constructor in the class. In this case, the java compiler throws an exception saying the constructor is unclear.
Some of the Features of Method Overloading are mentioned below:
Some of the advantages of method overloading are mentioned below:
By using the method overloading mechanism, static polymorphism is obtained. Method overloading decreases code complexity and controls writing different methods for the same functionality with a distinct signature. The reusability of code is acquired with overloading since a similar method is used for distinct functions.
About The Author:
Digital Marketing Course
₹ 9,999/-Included 18% GST
Buy Course₹ 29,999/-Included 18% GST
Buy Course