Java Reference
In-Depth Information
The
do...while
loop in the method
main
continues to execute as long as the user has
not entered 99, which allows the user to run the program as long as the user wishes. The
preceding sample run is self-explanatory.
In Java, several methods can have the same name within a
class
. This is called method
overloading or overloading a method name. Before we state the rules to overload a
method, let us define the following:
Two methods are said to have different formal parameter lists if both methods
have:
A different number of formal parameters, or
If the number of formal parameters is the same, then the data type of the
formal parameters,
in the order you list, must differ in at least one
7
position.
For example, consider the following method headings:
public void
methodOne(
int
x)
public void
methodTwo(
int
x,
double
y)
public void
methodThree(
double
y,
int
x)
public int
methodFour(
char
ch,
int
x,
double
y)
public int
methodFive(
char
ch,
int
x, String name)
These methods all have different formal parameter lists.
Now consider the following headings:
public void
methodSix(
int
x,
double
y,
char
ch)
public void
methodSeven(
int
one,
double
u,
char
firstCh)
The methods
methodSix
and
methodSeven
both have three formal parameters, and the
data type of the corresponding parameters is the same. Therefore, these methods have the
same formal parameter list.
To overload a method name, within a
class
, any two definitions of the method must
have different formal parameter lists.
Method overloading: Creating several methods, within a
class
, with the same name.
The signature of a method consists of the method name and its formal parameter list.
Two methods have different signatures if they have either different names or different
formal parameter lists. (Note that the signature of a method does not include the return
type of the method.)
Search WWH ::
Custom Search