Java Method Overloading 2022
Hello readers, in today’s topic, we will discuss methods of overloading in Java. These are fundamental concepts that must be remembered before writing a Java program. Before these, we also discussed Decision making & Loop Control in Java 2022, if you don’t know Hurry up Now! Previously we also described briefly various topics of Java such as Operator in Java, Data types of Java, Difference between C++ & Java, and many more which are really helpful for your better understanding. So without wasting time let’s dive into our topic:
If a class has two or more methods but has the same name but is different in parameters, it is known as Method Overloading.
we can be overloading a method by passing various parameters to a method.
Suppose you have to perform an addition of the given numbers but there can be any number of arguments if you write the method such as a(int, int) for two parameters, and b(int, int, int) for three parameters then it is difficult to the programmers as well as user to understand the behavior of the method because its name differs.
so we use the method of overloading to overcome the problem.
Method overloading increases the comprehensibility of the program.
Different ways to overload the method in java
In Java, there are two ways to overload the method
- By changing the number of parameters
- By changing the data type
By changing the number of parameters
In this method, we have declared two methods with the same name, the first sum() method performs the addition of two numbers and the second add method performs the addition of three numbers.
so here is an example of the method
class Adder{ static int sum(int a,int b){return a+b;} static int sum(int a,int b,int c){return a+b+c;} } class TestOverloading1{ public static void main(String[] args) { System.out.println(Adder.sum(10,10)); System.out.println(Adder.sum(10,10,10)); } }
Output:-
20 30
By changing the data type of the parameter
In this method, we have to create two methods but in different datatype, which means the first sum() takes two integer parameter and the second one take two double parameters.
so here is an example of the method
class Adder{ static int sum(int a, int b){return a+b;} static double sum(double a, double b){return a+b;} } class TestOverloading2 { public static void main(String[] args) { System.out.println(Adder.add(10,10)); System.out.println(Adder.add(12.3,12.6)); } }
Output:-
20 24.9
1 thought on “Java Method Overloading 2022”