Java Reference
In-Depth Information
public static int GetNumParts() { // accessor
return NumParts;
}
public String getName() { // accessor
return name;
}
public double getPrice() { // accessor
return price;
}
public void setPrice(double p) { // mutator
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
public void printPart() {
System.out.printf("\nName of part: %s\n", name);
System.out.printf("Price: $%3.2f\n", price);
}
public String toString() {
return "\nName of part: " + name + "\nPrice: $" + price + "\n";
}
} // end class Part
2.6.1 Testing the Class Part
When we write a class, we must test it to ensure it is working as it should. For the class Part , we must check that the
constructor is working properly, in other words, that the accessor methods return the correct values and the mutator
method sets the (new) price correctly.
We must also check that the class handles invalid prices properly. In Program P2.2, we create three part objects
(one with an invalid price) and print their name/price information. We then print the number of parts created by
calling GetNumParts . Before we run the test program, we should work out the expected output so we can predict what
a correct program should output. If the output matches our prediction, fine; if not, there is a problem that must be
addressed.
Program P2.2
public class PartTest{
// a program for testing the class Part
public static void main(String[] args) {
Part a, b, c; // declare 3 Part variables
// create 3 Part objects
a = new Part("Air Filter", 8.75);
 
Search WWH ::




Custom Search