Function or Method Overloading in Java with Example

In java the concept of Polymorphism is achieved in two ways:

1. Method Overloading
2. Method Overriding 

In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different.

Here we will discuss only the concept of Method Overloading:
// Demonstrate method overloading.
class MethodOverloadExample {
void overloadsample() {
System.out.println("overloadsample with void";
}
// Overload overloadsample for one integer parameter.
void overloadsample(int a) {
System.out.println("overloadsample with Integer value:  " + a);
}
// Overload overloadsample for two integer parameters.
void overloadsample(int a, int b) {
System.out.println("overloadsample with two  Integer  values" + a + " " + b);
}
// overload overloadsample for a double parameter
double overloadsample(double a) {
System.out.println("overloadsample with double value " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
MethodOverloadExample ob = new MethodOverloadExample();
double result;
// call all versions of overloadsample()
ob.overloadsample();
ob.overloadsample(10);
ob.overloadsample(10, 20);
result = ob.overloadsample(123.2);
System.out.println("Result of ob.overloadsample(123.2): " + result);

}
}

As you can see, overloadsample( ) is overloaded four times. The first version takes no parameters, the second takes one integer parameter, the third takes two integer parameters, and the fourth takes one double parameter. The fact that the fourth version of overloadsample( ) also returns a value is of no consequence relative to overloading, since return types do not play a role in overload resolution.

When an overloaded method is called, Java looks for a match between the arguments used to call the method and the method's parameters. However, this match need not always be exact. In some cases Java's automatic type conversions can play a role in overload resolution. For example, consider the following program:

No comments:

Post a Comment

Please Provide your feedback here