Method Overloading in Java
Method overloading in Java is used when we want to declare a method with the same method name while passing in different parameters. We can add more parameters or use different data types to tell Java which method should be executed.
Method Overloading with Number of Parameters
Consider this example of an Addition
class that contains methods to add numbers together.
class Addition {public static int addTwoNumbers(int num1, int num2) {return num1 + num2;}public static int addThreeNumbers(int num1, int num2, int num3) {return num1 + num2 + num3;}public static int addFourNumbers(int num1, int num2, int num3, int num4) {return num1 + num2 + num3 + num4;}}
Rather than declaring unique method names each time, we could just use one method name. This is where method overloading occurs.
class Addition {public static int addNumbers(int num1, int num2) {return num1 + num2;}public static int addNumbers(int num1, int num2, int num3) {return num1 + num2 + num3;}public static int addNumbers(int num1, int num2, int num3, int num4) {return num1 + num2 + num3 + num4;}}
With method overloading, we are declaring the same method name, but Java knows which method to run according to the number of parameters.
Method Overloading with Different Data Types
Additionally, we can overload methods using different data types. If we wanted to also be able to add double
instead of int
, then we can write:
class Addition {public static int addNumbers(int num1, int num2) {return num1 + num2;}public static int addNumbers(int num1, int num2, int num3) {return num1 + num2 + num3;}public static int addNumbers(int num1, int num2, int num3, int num4) {return num1 + num2 + num3 + num4;}public static double addNumbers(double num1, double num2) {return num1 + num2;}public static double addNumbers(double num1, double num2, double num3) {return num1 + num2 + num3;}public static double addNumbers(double num1, double num2, double num3, double num4) {return num1 + num2 + num3 + num4;}}
Conclusion
Method overloading is useful in this case because we want to provide one concept of adding numbers. Rather than declaring different method names, we can just overload the method, making the code cleaner and more concise.