Java Reference
In-Depth Information
This sets the price of
Part
object
p
to
24.95
. As before, the method will not allow an invalid price to be set. It will
validate the supplied price and print an appropriate message, if necessary. Using the constants declared in Section
2.4.1, here is
setPrice
:
public void setPrice(double p) {
if (p < MinPrice || p > MaxPrice) {
System.out.printf("Part: %s\n", name);
System.out.printf("Invalid price: %3.2f; Set to %3.2f\n", p, NullPrice);
price = NullPrice;
}
else price = p;
} //end setPrice
With this addition, we can think of
Part p
as shown in Figure
2-3
.
725
name
price
getName()
getPrice()
725
p
setPrice()
Figure 2-3.
Part
object with
setPrice()
added
Observe the direction of the arrow for
setPrice
; a value is being sent from the outside world to the private field
of the object.
Again, we emphasize the superiority of declaring a field
private
and providing mutator/accessor methods for it
as opposed to declaring the field
public
and letting a user class access it directly.
We could also provide methods to increase or decrease the price by a given amount or by a given percentage.
These are left as exercises.
As another exercise, write mutator methods for the
price
and
inStock
fields of the
Book
class.
2.5 Printing an Object's Data
To verify that our parts are being given the correct values, we would need some way of printing the values in an
object's fields.
2.5.1 Using an Instance Method (the Preferred Way)
One way of doing this is to write an instance method (
printPart
, say), which, when invoked on an object, will print
that
object's data. To print the data for
Part p
, we will write this:
p.printPart();
Here is the method:
public void printPart() {
System.out.printf("\nName of part: %s\n", name);
System.out.printf("Price: $%3.2f\n", price);
} //end printPart
Search WWH ::
Custom Search