You are on page 1of 2

Code:

//program to demostrate method overloading


class adder
{
int add(int a,int b)
{
return a+b;
}
int add(int a,int b,int c)
{
return a+b+c;
}
double add(double a,double b)
{
return a+b;
}
}
class methodOverload
{
public static void main(String arg[])
{
adder obj=new adder();
System.out.println(" sum = "+obj.add(2,3));
System.out.println(" sum = "+obj.add(2,3,5));
System.out.println(" sum = "+obj.add(5.3,7.2));
}
}

OUTPUT:
DESCRIPTION:

Method Overloading means that a function with same name performs different functions.

It means that the datatypes of parameters distinguish functions that have same name and hence
those functions are able to perform different operations.

In this code of method overloading, there are two classes adder and methodOverload. In the class
adder there are three methods with the name of add. In the first add method, we have two
variables a and b of int datatype whose sum is computed.In the second method,we have three
parameters a,b and c whose sum is getting returned. In the third method with the same name add,
there are two variables and b of datatype double, whose sum is getting computed.

In the second class named methodOverload , we have the main method and inside the main method
we create an object obj of class adder where memory is allocated using new operator.When using
the dot operator or period ,we call these methods the addition operation is performed and
argyments are passed.

When first add method is called 2 and 3 argument values of type int are added and result 5 is
computed.

When second add method is called , 2,3 and 5 argument values of parameters a,b and c of type int
are added and result 10 is computed.

When third add method is called ,double values 5.3 of a and 7.2 of b are passed to the function
when invoked and hence the result 12.5 is computed.

You might also like