Java Reference
In-Depth Information
Typically, the instance variables of a class are declared
private
so that the user of a class
does not have direct access to them. In general, every class has a set of accessor methods to
work with the instance variables. If the data members need to be modified, then the class
also has a set of mutator methods. Conventionally, mutator methods begin with the word
set
and accessor methods begin with the word
get
. You might wonder why we need
both mutator and accessor methods when we can simply make the instance variables
public
. However, look closely, for example, at the mutator method
setTime
of
the
class
Clock
. Before setting the time, it validates the time. On the other hand, if
the instance variables are all
public
, then the user of the class can put any values in the
instance variables. Similarly, the accessor methods only return the value(s) of an instance
variable(s); that is, they do not modify the values. A well-designed class uses
private
instance variables, accessor methods, and (if needed) mutator methods to implement the
OOD principle of encapsulation.
Example 8-8 further illustrates how classes are designed and implemented. The
class
Person
that we create in this example is very useful; we will use this
class
in subsequent
chapters.
EXAMPLE 8-8
Two common attributes of a person are the person's first name and last name. The typical
operations on a person's name are to set the name and print the name. The following
statements define a
class
with these properties (see Figure 8-18).
public class
Person
{
private
String firstName;
//store the first name
private
String lastName;
//store the last name
//Default constructor;
//Initialize firstName and lastName to empty string.
//Postcondition: firstName = ""; lastName = "";
public
Person()
{
firstName = "";
lastName = "";
}
//Constructor with parameters
//Set firstName and lastName according to the parameters.
//Postcondition: firstName = first; lastName = last;
public
Person(String first, String last)
{
setName(first, last);
}
Search WWH ::
Custom Search