Skip to content

Objectifying Coffee Vending Machine


As we did in MealOrder, you will pull out the "ingredients", i.e., the size of coffee and the creamer, into separate classes.

For reference, the MealOrder, Burger, etc. classes are here.

Step 1: Extract to Separate Classes

  • Pull out the size and creamer aspects of the coffee into their own classes.
  • First extract the size and creamer tests into their own classes, e.g., SizeTest and CreamerTest.
  • Then extract the code into the classes.
  • Make sure those tests work before moving on..

  • Change CoffeeOrder so that it has references to the Size and Creamer objects.

  • Ask yourself how CoffeeOrder knows how to create the appropriate Size and Creamer objects.

  • Change the price() method on CoffeeOrder so that it delegates the price to the size and creamer objects.

  • Make sure all of your tests continue to pass!

Do not continue unless all tests pass.

Step 2: Generalize Size and Creamer

  • Create a "base" class, CoffeeItem that has a price method:

      public int price() {
        return 0;
  • Change Size and Creamer so that they inherit from the base class and override the price() method.

  • All tests should still pass!

Step 3: CoffeeOrder Has List of Items

Check-In Point

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

Step 4: Add Sweetener Item

  • Add a new item, Sweetener, that has these options:

    • None: 0 cents
    • Sugar: 10 cents
    • Splenda: 15 cents
  • Make sure you have tests that try out a full coffee order with and without sugar.

Step 5: Support New Coffee Size

  • Add a new size of coffee that is "XL" (extra large) and costs $3.

    • Think about what you need to change.

    • Make sure tests continue to pass.

Step 6: Print Out a Coffee Order

  • Create a new display() method on CoffeeOrder that displays to the screen (using System.out.println()) the coffee order. For example:

    Size: Medium
    Creamer: Milk
    Sweetener: Sugar
    Price: 185
  • Think about what is in common across the different types of CoffeeItems -- how is this similar to price()?

In the main method in App, create a variety of CoffeeOrders and have them printed out.

Check-In Point

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

The next steps are optional...

Step 7: New Coffee Type: Latte

  • A new type of coffee, a Latte, can be ordered and is $4 (400 cents).

  • When the order is printed, it should show "Medium Latte, with Milk, $4"

Step 8: Display as Dollars

  • When displaying the CoffeeOrder, display the price as a dollar amount instead of in cents as in the highlighted line below:

    Size: Medium
    Creamer: Milk
    Sweetener: Sugar
    Price: $1.85