If there are two method, they have different parameters, and their return types are different. Like this:
int test(int p) {
System.out.println("version one");
return p;
}
boolean test(boolean p, int q) {
System.out.println("version two");
return p;
}
If the return types are same, of course this is overload. But since the return types are different, can we regard this as overload still?
To quote the official tutorial:
Having a different return type is inconsequential to overloading. In fact, this is quite common with methods that return one of their arguments. E.g.,
java.util.Math
has a bunch of overloadedmax
methods. Amax
of twoint
s return anint
, amax
of twodouble
s return adouble
, etc.In function overloading return types don't play any role. Function overloading can only be achieved via change in arguments. So, yes in your given case test() is overloaded
Yes, this is also an overload. Since only the name and the list of parameters are considered part of method's signature for the purposes of method overloading, both your
test
methods are overloads of each other.There may be useful scenarios for overloading a method like that, too. Consider this example:
A programmer who uses
Sanitizer
can write things likeand the overload makes the code looks the same for variables of different types.
consider following points for overloading:
1) First and important rule to overload a method in java is to change method signature. Method signature is made of number of arguments, type of arguments and order of arguments if they are of different types.
2) Return type of method is never part of method signature, so only changing the return type of method does not amount to method overloading.
3) Thrown exceptions from methods are also not considered when overloading a method. So your overloaded method throws the same exception, a different exception or it simply does no throw any exception; no effect at all on method loading.