We can easily create more than one method with a similar name but different parameters. Let’s say we have the following method:
1
2
3
intdemoAdd(inta,intb)
We can create more methods with the same name:
1
2
3
4
intdemoAdd(inta,intb)
doubledemoAdd(doublea,doubleb)
Above, we have different types and numbers of parameters for methods with similar names.
The 1st will add two integers and the 2nd two doubles. This is called Method Overloading. For the same action i.e., addition here, by overloading, we do not need to use different method names.
Let us see two examples:
We will add numbers of different types (int and double) when the number of parameters is the same
We will add integers when the number of parameters is different:
Add numbers of different types (int and double)
Let us see the 1st example. We will overload the demoAdd() method and add two integers and then two doubles:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
classStudyopedia{
// The demoAdd() method is overloaded
// Adding two integer values
staticintdemoAdd(inta,intb){
returna+b;
}
// Adding two double values
staticdoubledemoAdd(doublea,doubleb){
returna+b;
}
publicstaticvoidmain(String[]args){
intn1=demoAdd(10,20);
doublen2=demoAdd(2.75,5.78);
// Displaying the result
System.out.println("Adding two integers = "+n1);
System.out.println("Adding two doubles = "+n2);
}
}
Output
1
2
3
4
Adding two integers=30
Adding two doubles=8.530000000000001
Add integers of similar types but different counts of parameters
Let us see another example where we will add integers when the count of parameters is different:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
classStudyopedia{
// The demoAdd() method is overloaded
// Adding two integer values
staticintdemoAdd(inta,intb){
returna+b;
}
// Adding three integer values
staticintdemoAdd(inta,intb,intc){
returna+b+c;
}
publicstaticvoidmain(String[]args){
intn1=demoAdd(10,20);
intn2=demoAdd(25,35,50);
// Displaying the result
System.out.println("Adding two integers = "+n1);
System.out.println("Adding three integers = "+n2);
}
}
Output
1
2
3
4
Adding two integers=30
Adding three integers=110
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok
No Comments