Java Reference
In-Depth Information
2.4.2 Accessor Methods
Since a user class may need to know the name or price of an item, we must provide public accessor methods for name
and price . An accessor method simply returns the value in a particular field. By convention, we preface the name of
these methods with the word get . The methods are as follows:
public String getName() { // accessor
return name;
}
public double getPrice() { // accessor
return price;
}
Note that the return type of an accessor is the same as the type of the field. For example, the return type of
getName is String since name is of type String .
Since an accessor method returns the value in an instance field, it makes sense to call it only in relation to a
specific object (since each object has its own instance fields). If p is an object of type Part , then p.getName() returns
the value in the name field of p and p.getPrice() returns the value in the price field of p .
As an exercise, write accessor methods for all the fields of the Book class.
These accessors are examples of non-static or instance methods (the word static is not used in their
declaration). We can think of each object as having its own copy of the instance methods in a class. In practice,
though, the methods are merely available to an object. There will be one copy of a method, and the method will be
bound to a specific object when the method is invoked on the object.
Assuming that a Part object p is stored at location 725 , we can picture the object as shown in Figure 2-2 .
725
name
getName()
price
getPrice()
725
p
Figure 2-2. A Part object with its fields and accessors
Think of the fields name and price as locked inside a box, and the only way the outside world can see them is via
the methods getName and getPrice .
2.4.3 Mutator Methods
As the writer of the class, we have to decide whether we will let a user change the name or price of an object after it
has been created. It is reasonable to assume that the user may not want to change the name. However, prices change,
so we should provide a method (or methods) for changing the price. As an example, we write a public mutator method
( setPrice , say) that user classes can call, as in the following:
p.setPrice(24.95);
 
 
Search WWH ::




Custom Search