[go: up one dir, main page]

0% found this document useful (0 votes)
5 views2 pages

Method Overloading

Uploaded by

malalikhan605
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Method Overloading

Uploaded by

malalikhan605
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Method Overloading

Method Overloading is a feature of object oriented programming that allows a class to have two or more
methods having same name, if they have different method signatures, means that methods within a class
can have the same name but they have different set of parameter.
public class Calculator
{

public int add(int x, int y)


{
...
}
public int add(int x, int y, int z)
{
...
}
public double add(double x, double y, double z)
{
...
}
}

Overloaded methods are differentiated by the number and the type of the arguments passed into the
method. In the above given sample code, add(int x, int y, int z) and add(double x,
double y, double z) are distinct and unique methods because they require different argument types.

We cannot declare more than one method with the same name and the same number and type of
parameters in the class.

public class Calculator


{

public int add(int x, int y)


{
...
}
public int add(int x, int y)
{
...
}

The compiler does not consider return type when differentiating methods, so you cannot declare two
methods with the same signature even if they have a different return type.
Sample Program

package calculatorPackage;

public class Calculator


{
public int add(int a, int b)
{
return a + b;
}
public int add(int a, int b, int c)
{
return a + b + c;
}
public double add(double a, double b, double c)
{
return a + b + c;
}
}

package calculatorPackage;

public class TestClass


{
public static void main(String[] args)
{
Calculator c = new Calculator();

System.out.println(c.add(3,2));
System.out.println(c.add(2, 3, 5));
System.out.println(c.add(3.22,7.23,2.94));
}
}

Output

5
10
13.39

You might also like