Java Method Overloading

Method overloading is a feature which allows a class to have multiple methods with same name but different parameter list. There is difference between overloading and overriding. In overriding the method name, type and parameters should be the same in child class as of parent class but the behavior can be specific to the sub class.

See the below method overloading example

public class JavaOverloading{

// to sum integer values

public static int add(int a, int b) {

return a + b;

}

// to sum double values

public static double add(double a, double b) {

return a + b;

}

public static void main(String[] args) {

int a = 20;
int b = 65;
double c = 21.7;
double d = 12.8;

int sumint = add(a, b);
double sumdbl = add(c, d);
System.out.println(“Adding two integer values”);
System.out.println(“Result = ” + sumint);
System.out.println(“Adding two double values”);
System.out.println(“Result = ” + sumdbl);

}

}

Output

Adding two integer values
Result = 85
Adding two double values
Result = 34.5

Method overloading is also called static polymorphism or compile time binding. There cannot be two methods with same name and same number of parameters (parameter type) even if the return type is different.

Leave a Reply

Your email address will not be published. Required fields are marked *