Java Reference
In-Depth Information
object and operates on instance variables), so it could be misleading. We recommend that class (static) methods be
called via the class name rather than via an object from the class.
As an exercise, add a field to the Book class to count the number of book objects created and update the
constructors to increment this field.
2.4.1 An Improved Constructor
Instead of a no-arg constructor, we could take a more realistic approach and write a constructor that lets the user
assign a name and price when an object is created, as in the following:
Part af = new Part("Air Filter", 8.75);
We could write the constructor as:
public Part(String n, double p) {
name = n;
price = p;
NumParts++;
}
This will work except that a user can still set an invalid price for a part. There is nothing to stop the user from
writing this statement:
Part af = new Part("Air Filter", 199.99);
The constructor will dutifully set price to the invalid value 199.99 . However, we can do more in a constructor
than merely assign values to variables. We can test a value and reject it, if necessary. We will take the view that if an
invalid price is supplied, the object will still be created but a message will be printed and the price will be set to -1.0 .
Here is the new version of the constructor:
public Part(String n, double p) {
name = n;
if (p < 0.0 || p > 99.99) {
System.out.printf("Part: %s\n", name);
System.out.printf("Invalid price: %3.2f. Set to -1.0.\n", p);
price = -1.0;
}
else price = p;
NumParts++;
} //end constructor Part
As a matter of good programming style, we should declare the price limits ( 0.00 and 99.99 ) and the “null” price
( -1.0 ) as class constants. We could use the following:
private static final double MinPrice = 0.0;
private static final double MaxPrice = 99.99;
private static final double NullPrice = -1.0;
These identifiers can now be used in the constructor.
 
Search WWH ::




Custom Search