Difference between extends and implementsTopOverridingLaundry one more time

Laundry one more time

We've done laundry a few times already. Just be glad we didn't have pants and shirts falling from our clouds in the previous example.

We modified our original laundry sorter from lab to include a Laundry interface so that one variable could hold either Tshirts or Pants.

However, there was a still lot of overlap between the code for Tshirts and Pants. Using inheritance, we can "factor out" that common code into a superclass called LaundryImpl. See the new laundry code
Recall our program used the Laundry interface. Actual method bodies for the methods declared there appear in both Tshirt and Pants. However the code for the corresponding methods in each class are essentially the same. The only difference is the names and types of instance variables that correspond to the different pieces of a Tshirt (e.g., sleeves, neck, and body) or Pants (legs and waist).

Instead of having all those instance variables, we will hold the different components of each of the different kinds of laundry items in an array. The type of this array must be able to hold FramedRects, FilledRects, FramedOvals, and FilledOvals. There are actually several interfaces that are implemented by all of these, but we will use DrawableInterface, because it has all of the operations we need to use with laundry items. (We could also have used Drawable2DInterface, for example, as the different kinds of rects and ovals implement this interface as well.) See the on-line code above.

The instance variable parts is an array of DrawableInterface. It is created in the constructor, but no elements are added except in addComponent. The other methods use the array to iterate through the components, performing appropriate actions.

The methods move, moveTo, contains, removeFromCanvas, setColor, and getColor are all public because they implement the methods in the Laundry interface (all methods in an interface are by default public). The method addComponent is protected because it to be called only from classes that extend LaundryImpl.

Once we have LaundryImpl, we can create objects and use addComponent directly to build custom laundry items. We can simplify our Tshirt and Pants classes by having them extend LaundryImpl. We need only constructors, as the methods of LaundryImpl were designed carefully to work with all kinds of combinations of graphic elements. See the code for Tshirt and Pants. With inheritance, it becomes much simpler for us to extend this program with more subclasses representing additional laundry items.


Difference between extends and implementsTopOverridingLaundry one more time