METHODS OVERLOADING

If a class have multiple methods by same name but different parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.

Syntax

class  class_Name
{
Returntype  method()
{
...........
...........
}
Returntype  method(datatype1 variable1)
{
...........
...........
}
Returntype  method(datatype1 variable1, datatype2 variable2)
{
...........
...........
}
Returntype  method(datatype2 variable2)
{
...........
...........
}
Returntype  method(datatype2 variable2, datatype1 variable1)
{
..........
..........
}
}

Different ways to overload the method

There are two ways to overload the method in java
  • By changing number of arguments or parameters
  • By changing the data type

By changing number of arguments

In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers.

Example

class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
}

Output

30
60

By changing the data type

In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two float arguments.

Example

class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(float a, float b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10.05, 15.20);
}
}

Output

30
25.25

No comments:

Post a Comment