Java Reference
In-Depth Information
EXAMPLE:
(continued)
Note that there is a difference between what we might call the
inside view
and the
outside view
of the class
DateFifthTry
. A date like July 4, 1776, is represented inside
the class object as the string value
"July"
and the two
int
values
4
and
1776
. But if a
programmer using the same class object asks for the date using
getMonth
,
getDay
, and
getYear
, he or she will get the three
int
values
7
,
4
, and
1776
. From inside the class, a
month is a string value, but from outside the class, a month is an integer. The descrip-
tion of the data in a class object need not be a simple direct description of the instance
variables. (To further emphasize the fact that the month has an inside view as a string
but an outside view as a number, we have written the method
readInput
for the class
DateFifthTry
so that the user enters the month as an integer rather than a string.)
Note that the method definitions in a class need not be given in any particular order.
In particular, it is perfectly acceptable to give the definition the method dateOK after
the definitions of methods that use dateOK. Indeed, any ordering of the method defini-
tions is acceptable. Use whatever order seems to make the class easiest to read. (Those
who come to Java from certain other programming languages should note that there is
no kind of forward reference needed when a method is used before it is defined.)
Self-Test Exercises
15. Following the style guidelines given in this topic, when should an instance vari-
able be marked
private
?
16. Following the style guidelines given in this topic, when should a method be
marked
private
?
Accessor and Mutator Methods
You should always make all instance variables in a class private. However, you may
sometimes need to do something with the data in a class object. The special-purpose
methods, such as
toString
,
equals
, and any input methods, will allow you to do
many things with the data in an object. But sooner or later you will want to do
something with the data for which there are no special-purpose methods. How can
you do anything new with the data in an object? The answer is that you can do any-
thing that you might reasonably want (and that the class design specifications consider
to be legitimate), provided you equip your classes with suitable
accessor
and
mutator
methods. These are methods that allow you to access and change the data in an object,
usually in a very general way.
Accessor methods
allow you to obtain the data. In Dis-
play 4.9, the methods
getMonth
,
getDay
, and
getYear
are accessor methods. The
accessor methods need not literally return the values of each instance variable, but
accessor
methods