Home Segments Top Top Previous Next

325: Mainline

Deciding between a subclass–superclass relation and a part–whole relation is not always straightforward. For example, you may decide to model a piano as an instrument that has a keyboard, or you may decide to model a piano as a keyboard instrument. If you follow the has-a rule, you implement the Piano class with a Keyboard instance variable; if you follow the is-a rule, you implement the Piano class as a subclass of the KeyboardInstrument class.

The rule you should follow is the one that seems to make the most sense in light of the aspects of the real world that you are modeling. If your program is to deal with many types of keyboard instruments, then defining a KeyboardInstrument class probably is the better choice. If your program is to deal with only pianos, then defining a Keyboard instance variable probably is the better choice.

Thus, there is no universal right answer to the decision between modeling with the subclass–superclass relation and the part–whole relation.