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.
-
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¶
-
Change both
Creamer
andSweetener
classes toextends
fromQuantityItem
.Keep the implements
Both classes must still use
implements
for theCoffeeItem
interface. -
In both the
Creamer
andSweetener
classes, rename theprice()
method to bebasePrice()
.Keep @Override
The
basePrice()
method should still keep the@Override
annotation. -
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.
-
In
Sweetener
, remove theprivate int quantity
member variable. -
Run the
SweetenerTest
. What happens? -
The responsibility of multiplying by quantity is no longer needed in
Sweetener
, since it's implemented inQuantityItem
. -
Remove the use of
quantity
from thebasePrice()
method. -
Run the
SweetenerTest
. -
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.