Java Reference
In-Depth Information
b = new Part("Ball Joint", 29.95);
c = new Part("Headlamp", 199.99); // invalid price
a.printPart(); // should print Air Filter, $8.75
b.printPart(); // should print Ball Joint, $29.95
c.printPart(); // should print Headlamp, $-1.0
c.setPrice(36.99);
c.printPart(); // should print Headlamp, $36.99
// print the number of parts; should print 3
System.out.printf("\nNumber of parts: %d\n", Part.GetNumParts());
} //end main
} // end class PartTest
When Program P2.2 is run, the following output is produced:
Part: Headlamp
Invalid price: 199.99; Set to -1.0
Name of part: Air Filter
Price: $8.75
Name of part: Ball Joint
Price: $29.95
Name of part: Headlamp
Price: $-1.0
Name of part: Headlamp
Price: $36.99
Number of parts: 3
This is the expected output, so we are assured that the class is working as it should.
Here's a final word on the Part class. If, for some strange reason, the class Part did not provide a printPart or
a toString method, a user class can write its own method to print a part's fields. However, it would have to use the
accessor methods of Part to get at an object's data since it cannot reference the private fields directly. The following
shows how to do this:
public static void printPart(Part p) {
// a method in a user class
System.out.printf("\nName of part: %s\n", p.getName());
System.out.printf("Price: $%3.2f\n", p.getPrice());
}
From the user class, we can write this:
Part af = new Part("Air Filter", 8.75);
printPart(af);
Search WWH ::




Custom Search