Overloading is a mechanism in which we can use many methods having the same function name but can pass different number of parameters or different types of parameter.
UNIT II : Inheritance, Packages and Interfaces
Overloading Methods
Overloading
is a mechanism in which we can use many methods having the same function name
but can pass different number of parameters or different types of parameter.
For
example:
int
sum(int a,int b);
double
sum(double a, double b);
int
sum(int a,int b,int c);
That
means, by overloading mechanism, we can handle different number of parameters
or different types of parameter by having the same method name.
Following
Java program explains the concept overloading -
Java
Program [OverloadingDemo.java]
public
class OverloadingDemo {
public
static void main(String args[]) {
System.out.println("Sum
of two integers");
Sum(10,20);
<-------------- line A
System.out.println("Sum
of two double numbers");
Sum(10.5,20.4);
<------------ line B
System.out.println("Sum
of three integers");
Sum(10,20,30);
<‒‒‒‒‒‒‒‒‒‒‒ line C
}
public
static void Sum(int num1,int num2)
{
int ans;
ans
num1+num2;
System.out.println(ans);
}
public
static void Sum(double num1,double num2)
{
double
ans;
ans
num1+num2;
System.out.println(ans);
}
public
static void Sum(int num1,int num2,int num3)
{
int ans;
ans
num1+num2+num3;
System.out.println(ans)
}
}
Output
F:\test>javac
OverloadingDemo.java
F:\test>java
OverloadingDemo
Sum of
two integers
30
Sum of
two double numbers
30.9
Sum of
three integers
60
Program
Explanation
In above
program, we have used three different methods possessing the same name. Note
that,
on line A
We have
invoked a method to which two integer parameters are passed. Then compiler
automatically selects the definition public static void Sum(double num1,double
num2) to fulfill the call. Hence we get the output as 30 which is actually the
addition of 10 and 20.
on line B
We have
invoked a method to which two double parameters are passed. Then compiler
automatically selects the definition public static void Sum(double num1,double
num2) to fulfill the call. Hence we get the output as 30.9 which is actually
the addition of 10.5 and 20.4.
on line C
We have
invoked a method to which the three integer parameters are passed. Then compiler
automatically selects the definition public static void Sum(int num1,int
num2,int num3) to fulfill the call. Hence we get the output as 60 which is
actually the addition of 10, 20 and 30.
Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces : Tag: : with Example Java Programs - Overloading Methods
Object Oriented Programming
CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation