Skip to content

Interfaces vs. Subclassing


Replace the somewhat useless base class with an interface and allow creamer and sweetener to have a quantity associated with them.

A. Change CoffeeItem to an Interface

  1. Change CoffeeItem so that instead of public class CoffeeItem, you have public interface CoffeeItem.

  2. Since we don't need the implementation of price() in the interface, remove the code and all you should be left with is:

    int price();

    Java Coding Style

    Interface methods are always the same "visibility" as the interface itself, in this case public, so putting public before the method is redundant, so coding style tells us to leave it out.

  3. Try and run the tests and see the error messages that are displayed.

B. Make Subclasses Implement the Interface

  1. For the Creamer and Sweetener, replace extends CoffeeItem with implements CoffeeItem.

  2. Run all the tests. Do they pass?

C. Add Quantity to Creamer and Sweetener

In this step, we want the ability to have multiple of the same creamer and/or sweetener in our coffee. For example, we want a coffee with 2 portions of milk and 3 sugars.

  1. Create a new (overloaded) constructor that accepts the quantity amount in addition to the type of Creamer/Sweetener. For example:

    public Creamer(String creamerType, int quantity)
  2. Add a new failing test to the CreamerTest class that exercises the new quantity. For example:

    public void twoMilksCosts50() throws Exception {
      Creamer milks = new Creamer("milk", 2);
  3. Update the price() method in Creamer to take into account the quantity to make the test pass.

    • You'll want to store the quantity as an int member (instance) variable.
  4. Make sure Creamer still supports the default quantity of one through the constructor that takes just the type of creamer, i.e., this test should continue to pass:

    public void halfNhalfCosts35() throws Exception {
      Creamer halfnhalf = new Creamer("half-n-half");
  5. Now do the same changes to Sweetener:

    • Write a (failing) test first in the SweetenerTest class that specifies a quantity of more than 1
    • Then write the code to make it pass.

Once you've completed the above steps, check in with the instructor.