| < Day Day Up > |
AccessorsIn most, if not all, examples in this book, the attributes are defined as private so that a second object cannot access another object's attributes. It would be ridiculous to create an object in isolation ”we want to share the appropriate information with other objects. Isn't it necessary to inspect and sometimes change another class's attribute? 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 about 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
// 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 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 information. 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
Figure 4.4. Asking for information.
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
Objects
Actually, there isn't a physical copy of each nonstatic method for each object. Each object would point to the same physical code. However, from a conceptual level, you can think of objects as being
The following code fragment illustrates how to define a static method, and Figure 4.5 shows how more than one object points to the same code. Figure 4.5. Method memory allocation.
Static Attributes If an attribute is static, and the class provides a setter for that attribute, any object that invokes the setter will change the single copy. Thus, the value for the attribute will change for all objects.
// Get the Name of the Cabbie
public static String getCompanyName() {
return companyName;
}
|
| < Day Day Up > |