Java Reference
In-Depth Information
The setters here are very simple; they don't include any of the validity checks or access restrictions
that were said to be the main advantages of information hiding. You might start by making setID()
private. It seems logical that a Product 's ID number should not be changeable from outside the class.
Remember, if you want to ensure that a Product 's ID number never changes, you can make that vari-
able final as well. Now, to deal with the problem identified in the beginning: negative prices should
not be allowed. You can add a check to see if the price is above 0, or you might store a minimum and
maximum price to compare your price against. The second option is demonstrated in the next version
of the Product class. First, two static variables have been added to indicate the absolute minimum
and maximum prices any product can have. Then another method was added to compare any poten-
tial price to the minimum and maximum to see if it is a valid price. Finally, the setPrice() method
uses the isValidPrice() method to check the price provided. If it is not valid, the method throws an
IllegalArgumentException . Otherwise, the price is set to the provided price.
import java.math.BigDecimal;
 
public class Product {
private static BigDecimal minPrice = new BigDecimal("0.00");
private static BigDecimal maxPrice = new BigDecimal("999.99");
private String productName;
private String productID;
private BigDecimal productPrice;
 
public Product(String name, String id, String price) {
this.setName(name);
this.setID(id);
this.setPrice(price);
}
 
public String getName(){
return this.productName;
}
 
public void setName(String name){
this.productName = name;
}
 
public String getID(){
return this.productID;
}
 
private void setID(String id){
this.productID = id;
}
 
public BigDecimal getPrice(){
return this.productPrice;
}
 
public void setPrice(String price) throws IllegalArgumentException{
BigDecimal tempPrice = new BigDecimal(price);
if (!isValidPrice(tempPrice)){
throw new IllegalArgumentException(price);
Search WWH ::




Custom Search