Java Reference
In-Depth Information
Self-Test Exercises
(continued)
19. Write a better version of the method
dateOK
with three
int
parameters
(Display 4.9). This version should check for the correct number of days in each
month and should not just allow 31 days in any month. It will help to defi ne
another helping method named
leapYear
, which takes an
int
argument for
a year and returns
true
if the year is a leap year. February has 29 days in leap
years and only 28 days in other years. Use the following rule for determining
if the year is a leap year: A year is a leap year if it is divisible by 4 but is not
divisible by 100, or if it is divisible by 400.
4.3
Overloading
A good name is better than precious ointment.
Ecclesiastes 7:1
Two (or more) different classes can have methods with the same name. For example,
many classes have a method named
toString
. It is easy to see why this is acceptable. The
type of the calling object allows Java to decide which definition of the method
toString
to use. It uses the definition of
toString
given in the definition of the class for the calling
object. You may be more surprised to learn that two or more methods
in the same class
can
have the same method name. This is called
overloading
and is the topic of this section.
overloading
Rules for Overloading
In Display 4.11, we have added two methods named
setDate
to our date class so that
there is a total of three methods named
setDate
. This is an example of overloading the
method name
setDate
. On the following three lines, we display the headings of these
three methods:
public void
setDate(
int
month,
int
day,
int
year)
public void
setDate(String month,
int
day,
int
year)
public void
setDate(
int
year)
Notice that each method has a different parameter list. The first two differ in the type
of their first parameter. The last one differs from the other two by having a different
number of parameters.
The name of a method and the list of parameter types in the heading of the method
definition is called the
method signature
. The signatures for these three method
definitions are
Method
signature
setDate(
int
,
int
,
int
)
setDate(String,
int
,
int
)
setDate(
int
)