Interfaces vs. Subclassing¶
Goal¶
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¶
-
Change
CoffeeItem
so that instead ofpublic class CoffeeItem
, you havepublic interface CoffeeItem
. -
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 puttingpublic
before the method is redundant, so coding style tells us to leave it out. -
Try and run the tests and see the error messages that are displayed.
B. Make Subclasses Implement the Interface¶
-
For the
Creamer
andSweetener
, replaceextends CoffeeItem
withimplements CoffeeItem
. -
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.
-
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)
-
Add a new failing test to the CreamerTest class that exercises the new quantity. For example:
@Test public void twoMilksCosts50() throws Exception { Creamer milks = new Creamer("milk", 2); assertThat(milks.price()) .isEqualTo(50); }
-
Update the
price()
method inCreamer
to take into account the quantity to make the test pass.- You'll want to store the quantity as an
int
member (instance) variable.
- You'll want to store the quantity as an
-
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:@Test public void halfNhalfCosts35() throws Exception { Creamer halfnhalf = new Creamer("half-n-half"); assertThat(halfnhalf.price()) .isEqualTo(35); }
-
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.
- Write a (failing) test first in the
Once you've completed the above steps, check in with the instructor.