Skip to content

Reuse via Subclassing Abstractly

In this lab, we'll actually reuse code with subclasses and introduce a new concept, 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.

A. Create the Base Behavior

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

  1. 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();
    }
    

B. Subclass and Inherit QuantityItem's Behavior

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

    Keep the 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.

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

C. 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?

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

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

  5. Run the SweetenerTest.

  6. Do the same thing 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.