Java Reference
In-Depth Information
}
this.productPrice = tempPrice;
}
 
public boolean isValidPrice(BigDecimal price){
if (price.compareTo(minPrice)<0){
return false;
}
if (price.compareTo(maxPrice)>0){
return false;
}
return true;
}
 
public String displayString() {
return "Product " + this.getID() + ": " + this.getName()
+ " costs " + this.getPrice();
}
}
Now, you just need to adapt your ProductProgram class to use these new methods. You will use the
setPrice() method to change the price of myWidget . Because it can throw an exception, use the
try-catch blocks you learned about in the previous chapter to handle the exception appropriately.
One way you could do this is shown in the next code example.
public class ProductProgram {
public static void main(String[] args) {
Product myWidget = new Product("Widget","WID0001","11.50");
 
try {
myWidget.setPrice("-5.0");
} catch (IllegalArgumentException e){
System.out.println(e + " is an invalid price.");
}
System.out.println(myWidget.displayString());
}
}
Try running the program with different price values to see what happens. Or better yet, use
unit testing from Chapter 6 to test all the possible cases. You might also have noticed that the
ProductProgram class no longer uses the BigDecimal class because the setPrice() method takes
a String as the parameter. This means that even if you decide later to use a different data type in the
Product class, you would not have to change anything in the ProductProgram class.
Information hiding or encapsulation
try it out
In this exercise, you start with a simple Bank Account application and adapt it to apply the principles of
information hiding.
1.
If you do not already have a project in Eclipse for Chapter 7, create one now.
2.
Create a new class by right‐clicking on the src folder in your new project. Select New and then Class.
Name the new class Account . Uncheck the box to create a main method. This class should look like this:
Search WWH ::




Custom Search