Skip to content

Interfaces vs. Subclassing

Goal

Use an interface instead of a base class.

Step 1: Change CoffeeItem to an Interface

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

  • Try and compile/run your app and see the error messages that are displayed.

Step 2: Make Subclasses Implement the Interface

  • Go through all of the coffee items (size, creamer, sweetener), replacing extends CoffeeItem with implements CoffeeItem.

  • Run all the tests. Do they all pass?

Step 3: Add Quantity to Creamer and Sweetener

In this step, we want the ability to have multiple creamers and sweeteners in our coffee.

  • In both the Creamer and Sweetener classes, add a member variable int quantity and have it default to 1.

  • Create overloaded constructors that accept the quantity amount in addition to the type of Creamer/Sweetener. For example:

    public Creamer(String creamerType, int quantity)
    
  • Update the price() methods in both Creamer/Sweetener that multiply the price by the quantity.

  • Write a few tests that specify a quantity other than 1 (try 2 or 3) and make sure that they calculate the price correctly.


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