Reuse via Subclassing Abstractly¶
In this lab, we'll actually reuse code with subclasses and use the concept of 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.
Step 1. 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();
}
Step 2. Subclass and Inherit QuantityItem's Behavior¶
-
Change both
Creamer
andSweetener
classes toextends
fromQuantityItem
.Don't remove
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, since it overrides the method defined inQuantityItem
. -
Everything should still compile and pass all the tests.
Step 3. 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
.The tests should pass.
-
Do these steps 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.