Java Reference
In-Depth Information
Since it is not clear what it means to print an arbitrary object, Java will look for guidance in the class itself.
Presumably, the class will know how to print its objects. If it provides a toString method, Java will use it. (If it
doesn't, Java will print something generic like the name of the class and the address, in hexadecimal, of the object, for
instance: Part@72e15c32 .) In our example, we could add the following to the class Part :
public String toString() {
return "\nName of part: " + name + "\nPrice: $" + price + "\n";
}
If af is the Air Filter part, then the following statement would invoke the call af.toString() :
System.out.printf("%s", af);
In effect, the printf becomes this:
System.out.printf("%s", af.toString());
af.toString() will return this:
"\nName of part: Air Filter \nPrice: $8.75\n"
The result is that printf will print this:
Name of part: Air Filter
Price: $8.75
2.6 The Class Part
Putting all the changes together, the class Part now looks like this:
public class Part {
// class constants
private static final double MinPrice = 0.0;
private static final double MaxPrice = 99.99;
private static final double NullPrice = -1.0;
private static int NumParts = 0; // class variable
private String name; // instance variable
private double price; // instance variable
public Part(String n, double p) { // constructor
name = n;
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;
NumParts++;
} //end constructor Part
 
Search WWH ::




Custom Search