11. Writing Classes 4
A simple exercise writing some classes. Uses ArrayList.
You are going to work with a list of stored items and their amounts, like this:
Food 500
Water 300
Food 200
Fish 7
Water 800
Supply Class
The first step is to write a Supply
class that will hold one line of
information.
Supply food1 = new Supply("Food", 500);
System.out.println(food1); // "500 Food"
Include a method to make the Supply object print out as shown above.
Add in two more methods:
public boolean sameKind(Supply other) { ... }
public combineWith(Supply other) { ... }
The sameKind
method returns true when the two supplies have the same
kind. The combineWith
method has the precondition that the
this.sameKind(other)
is true. It changes the object by adding the
amount of the other object to it.
StoreRoom class
The StoreRoom
represents the information in a list of supplies, as
shown at the start. It has a void combineAll()
method that combines
all matching supplies into one.
// You set up contents = an ArrayList of Supplies.
System.out.println(contents);
// [500 Food, 300 Water, 200 Food, 7 Fish, 800 Water]
StoreRoom room030 = new StoreRoom(contents);
room030.combineAll();
System.out.println(room030);
// [700 Food, 1100 Water, 7 Fish]
Write the StoreRoom
class.