Java Reference
In-Depth Information
EXAMPLE:
Yet Another Date Class
Display 4.9 contains another, much improved, definition of a class for a date. Note
that all instance variables are private and that two methods are private. We made the
methods
dateOK
and
monthString
private because they are just helping methods
used in the definitions of other methods. A user of the class
DateFifthTry
would
not (in fact, cannot) use either of the methods
dateOK
or
monthString
. This is
all hidden information that need not concern a programmer using the class. The
method
monthString
was public in previous versions of our date classes because we
had not yet discussed the
private
modifier. It is now marked
private
because it is
just a helping method.
Note that the class
DateFifthTry
uses the method
dateOK
to make sure that
any changes to instance variables make sense. Because the methods of the class
DateFifthTry
use the method
dateOK
to check for impossible dates, you cannot
use any methods, such as
readInput
or
setDate
, to set the instance variables so that
they represent an impossible date such as January 63, 2005. If you try to do so, your
program would end with an error message. (To make our definition of the method
dateOK
simple, we did not check for certain impossible dates, such as February 31,
but it would be easy to exclude these dates as well.)
The methods
dateOK
and
equals
each return a value of type
boolean
. That
means they return a value that is either
true
or
false
and so can be used as
the Boolean expression in an
if-else
statement,
while
statement, or other loop
statement. This is illustrated by the following, which is taken from the definition of
the method
setDate
in Display 4.9 :
if
(dateOK(month, day, year))
{
this
.month = monthString(month);
this
.day = day;
this
.year = year;
}
else
{
System.out.println("Fatal Error");
System.exit(0);
}
Note that, although all the instance variables are private, a programmer using the
class can still change or access the value of an instance variable using the methods that
start with
set
or
get
. This is discussed more fully in the next subsection, “Accessor
and Mutator Methods.”
(continued)