Skip to content

Reuse via Subclassing Abstractly

In this lab, we'll actually reuse code with subclasses and use the concept of abstract. In the previous lab, we had two classes that did something similar: multiply the "base" price of the item by its quantity. Instead of have two places where we do the same thing, we can "pull up" the common code to a base class.

Step 1. Create the Base Behavior

This class will hold the behavior for multiplying the individual price of the item by the quantity.

Create a new class, QuantityItem that looks like this:

public abstract class QuantityItem {
  protected int quantity = 1;

  public int price() {
    return basePrice() * quantity;
  }

  public abstract int basePrice();
}

Step 2. Subclass and Inherit QuantityItem's Behavior

  1. Change both Creamer and Sweetener classes to extends from QuantityItem.

    Don't remove implements

    Both classes must still use implements for the CoffeeItem interface.

  2. In both the Creamer and Sweetener classes, rename the price() method to be basePrice().

    Keep @Override

    The basePrice() method should still keep the @Override annotation, since it overrides the method defined in QuantityItem.

  3. Everything should still compile and pass all the tests.

Step 3. Remove Quantity from Sweetener and Creamer

Since QuantityItem does the work of multiplying the base price by quantity, we should remove any reference to quantity from the subclasses.

  1. In Sweetener, remove the private int quantity member variable.

  2. Run the SweetenerTest. What happens?

    The responsibility of multiplying by quantity is no longer needed in Sweetener, since it's implemented in QuantityItem.

  3. Remove the use of quantity from the basePrice() method.

  4. Run the SweetenerTest.

    The tests should pass.

  5. Do these steps for Creamer, making sure the tests fail and then pass as expected.


Once you've completed the above steps, check in with the instructor to review your code.