created March 13, 2009


Programming Exercises


1.   Better encapsulation of the Goods class would call making instance variables private and using getter and setter methods to access them. A further refinement would be to make the class abstract and to define additional child classes. Here is a revised Goods class:

public abstract class GoodsSGA
{
  private String description;
  private double price;
  private int quantity;

  public GoodsSGA( String des, double pr, int quant )
  {
    description = des;
    price       = pr;
    quantity    = quant;
  }

  double getPrice()
  {
    return price;
  }

  void setPrice( double newPrice)
  {
    price =  newPrice;
  }

  int getQuantity()
  {
    return quantity;
  }

  void setQuantity ( int newQuantity )
  {
    quantity =  newQuantity;
  }
       
  public String toString()
  {
    return "item: " + description + " quantity: " + quantity + " price: " + price ;
  }
}

Revise the source code for the classes Food, Toy, and Book. (Perhaps call the revised classes FoodSG, ToySG, and BookSG.) create a new class ToiletrySG for things like bubble bath. Create a new testing class, StoreSG to test your revised classes.

Note: the child classes will need to use the getter and setter methods to access the instance variables that are declared as private in GoodsSG.


Click here to go back to the main menu.