Java Reference
In-Depth Information
accessor methods need not literally return the values of each instance variable, but they
must return something equivalent to those values. For example, the method getMonth
returns the number of the month, even though the month is stored in a String
instance variable. Although it is not required by the Java language, it is a generally
accepted good programming practice to spell the names of accessor methods starting
with get .
Mutator methods allow you to change the data in a class object. In Display 4.9, the
methods whose names begin with the word set are mutator methods. It is a generally
accepted good programming practice to use names that begin with the word set for
mutator methods. Your class definitions will typically provide a complete set of public
accessor methods and at least some public mutator methods. There are, however,
important classes, such as the class String , that have no public mutator methods.
At first glance, it may seem as if accessor and mutator methods defeat the purpose
of making instance variables private, but if you look carefully at the mutator methods
in Display 4.9, you will see that the mutator and accessor methods are not equivalent
to making the instance variables public. Notice the mutator methods, that is, the ones
that begin with set . They all test for an illegal date and end the program with an error
message if there is an attempt to set the instance variables to any illegal values. If the
variables were public, you could set the data to values that do not make sense for a date,
such as January 42, 1930. With mutator methods, you can control and filter changes to
the data. (As it is, you can still set the data to values that do not represent a real date, such
as February 31, but as we already noted, it would be easy to exclude these dates as well.
We did not exclude these dates to keep the example simple. See Self-Test Exercise 19 for
a more complete date check method.)
mutator
methods
Display 4.9
Yet Another Date Class (part 1 of 4)
1 import java.util.Scanner;
2 public class DateFifthTry
3{
4
private String month;
5
private int day;
6
private int year; //a four digit number.
7
public void writeOutput()
8
{
9
System.out.println(month + " " + day + ", " + year);
10
}
Note that this version of readInput has the user
enter the month as an integer rather than as a
string. In this class, a month is an integer to the
user, but is a string inside the class.
11
public void readInput()
12
{
(continued)
 
Search WWH ::




Custom Search