Java Reference
In-Depth Information
The following is an example of an incorrect attempt to overload the
m2()
method in class
OME2
:
// Won't compile
public class OME2 {
public void m2(int p1) {
// Code goes here
}
public void m2(int p2) {
// Code goes here
}
}
Using different names for parameters (
p1
and
p2
) does not make the
m2()
method overloaded. The code for the
OME2
class would not compile because it has a duplicate declaration for the
m2()
method. Both methods have the
same number and type of parameters, which makes it not overloaded.
The order of the parameters may play a role in making a method overloaded. The
m3()
method of the
OME3
class
is overloaded because parameter types are different. Both methods have one parameter of type
int
and another of
type
double
. However, they are in a different order.
public class OME3 {
public void m3(int p1, double p2) {
// Code goes here
}
public void m3(double p1, int p2) {
// Code goes here
}
}
Use a simple rule to check if two methods can be termed as an overloaded method. List the name of the methods
and the type of their parameters from left to right separated by a comma. You can use any other separator. If the
two methods of a class having the same name give you different lists, they are overloaded. Otherwise, they are not
overloaded. If you make such lists for
m1()
,
m2()
, and
m3()
methods in class
OME1
,
OME2
, and
OME3
classes, you will
come up with the following results:
// Method list for m1 in class OME1 - Overloaded
m1,int
m1,int,int
m1,String
m1,String,int
// Method list for m2 in class OME2 - Not Overloaded
m2,int
m2,int
// Method list for m3 in class OME3 - Overloaded
m3,int,double
m3,double,int