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
CreamerandSweetenerclasses toextendsfromQuantityItem.Don't remove
implementsBoth classes must still use
implementsfor theCoffeeIteminterface. -
In both the
CreamerandSweetenerclasses, rename theprice()method to bebasePrice().Keep @Override
The
basePrice()method should still keep the@Overrideannotation, 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 quantitymember 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
quantityfrom 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.
Once you've completed the above steps, check in with the instructor to review your code.