Java Reference
In-Depth Information
If a method's name is overloaded, then all the methods (with the same name) have
different signatures if they have different formal parameter lists. Thus, the following
method headings correctly overload the method
methodXYZ
:
public void
methodXYZ()
public void
methodXYZ(
int
x,
double
y)
public void
methodXYZ(
double
one,
int
y)
public void
methodXYZ(
int
x,
double
y,
char
ch)
Consider the following method headings to overload the method
methodABC
:
public void
methodABC(
int
x,
double
y)
public int
methodABC(
int
x,
double
y)
Both method headings have the same name and same formal parameter list. Therefore,
these method headings to overload the method
methodABC
are incorrect. In this case, the
compiler will generate a syntax error. (Note that the return types of these method
headings are different.)
If a method's name is overloaded, then in a call to that method, the formal parameter list
of the method determines which method to execute.
Some authors define the signature of a method as the formal parameter list; other authors
consider the entire heading of the method as its signature. In this topic, the signature of a
method consists of the method's name and its formal parameter list. If the method names
are different, then, of course, the compiler would have no problem identifying which
method is called and correctly translating the code. However, if a method name is
overloaded, then, as noted, the method's formal parameter list determines which
method's body executes.
Suppose you need to write a method that determines the larger of two items. Both items
can be integers, floating-point numbers, characters, or strings. You could write several
methods as follows (we give only the method heading):
int
largerInt(
int
x,
int
y)
char
largerChar(
char
first,
char
second)
double
largerDouble(
double
u,
double
v)
String largerString(String first, String second)
The method
largerInt
determines the larger of two integers, the method
largerChar
determines the larger of two characters, and so on. All of these methods perform similar
operations. Instead of giving different names to these methods, you can use the same name—
say,
larger
—for each method; that is, you can overload the method
larger
as follows:
int
larger(
int
x,
int
y)
char
larger(
char
first,
char
second)
double
larger(
double
u,
double
v)
String larger(String first, String second)
Search WWH ::
Custom Search