81
Accessors
ate information. Isn’t it necessary to inspect and sometimes change another class’s attrib-
ute? The answer is yes, of course.There are times when an object needs to access another
object’s attributes; however, it does not need to do it directly.
A class should be very protective of its attributes. For example, you do not want object
A to have the capability to inspect or change the attributes of object B without object B
having control.There are several reasons for this; the most important reasons really boil
down to data integrity and efficient debugging.
Assume that there is a bug in the Cab class.You have tracked the problem to the Name at-
tribute. Somehow it is getting overwritten, and garbage is turning up in some name
queries. If Name were public and any class could change it, you would have to go searching
through all the possible code, trying to find places that reference and change Name.How-
ever, if you let only a
Cabbie object change Name, you’d only have to look in the Cabbie
class.This access is provided by a type of method called an accessor. Sometimes accessors are
referred to as getters and setters, and sometimes they’re simply called get() and set().By
convention, in this book we name the methods with the set and get prefixes, as in the fol-
lowing:
// Set the Name of the Cabbie
public void setName(String iName) {
name = iName;
}
// Get the Name of the Cabbie
public String getName() {
return name;
}
In this code snippet, a Supervisor object must ask the Cabbie object to return its
name (see Figure 4.4).The important point here is that the Supervisor object can’t
simply retrieve the information on its own; it must ask the Cabbie object for the infor-
mation.This concept is important at many levels. For example, you might have a
setAge() method that checks to see whether the age entered was 0 or below. If the age
is less than 0, the
setAge() method can refuse to set this incorrect value. In general, the
setters are used to ensure a level of data integrity.
This is also an issue of security.You may have sensitive data, like passwords or payroll
information that you want to control access to.Thus, accessing data via getters and setters
provides the ability to use mechanisms like password checks and other validation tech-
niques.This greatly increases the integrity of the data.
Notice that the getCompanyName method is declared as static, as a class method; class
methods are described in more detail in Chapter 3. Remember that the attribute
companyName is also declared as static.A method, like an attribute, can be declared
static to indicate that there is only one copy of the method for the entire class.