If a class has multiple methods with same name but differ in type or number of parameters, is known as Method Overloading.
Method overloading increases the readability of the program.
There are two ways to overload the method in java
- By changing number of arguments
- By changing the data type
Example:
class mOverload{
static int add(int x, int y) {
return x +
y;
}
static double add(double x, double y) {
return x +
y;
}
public static void main(String[] args) {
int myNum1 =
add(8, 5);
double
myNum2 = add(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
}
In the above example, there are two methods with
same name (add), but the methods differ in type of parameters. One method is
used to add integers and other method is used to add floating point numbers.
No comments:
Post a Comment