Is-a Relationship
We have explored code reuse via inheritance. It is important to stress here the semantics of inheritance. Aside from reusing the implementation of the Student
class, we've created a well-defined "is-a" relationship between the base type Student
and the subtype GradStudent
.
Inheritance should be used to model "is-a" relationships, the code reuse is an added advantage.
It's all too easy to misuse inheritance merely for code reuse. Inheritance is intended for creating type hierarchies. Before employing it, you must put it to "is-a" test: if you can replace GradStudent
and Student
in the following sentence with your subtype and base type, and the sentence actually makes sense, then inheritance is the way to go.
GradStudent
is aStudent
with added attributes and/or behaviors.
Has-a relationship
The is-a relationship (inheritance) can be contrasted with the has-a relationship (composition) between types (classes).
Composition
When one type is made up of other types. It too can be used to achieve code reuse and polymorphism.
For example, the roster is made up of students: Roster
has-a Student
. (The has-a relationship does not imply a multiplicity of one; a Roster
has zero or more Student
).
Exercise We are building a software solution for an automobile repair company. So far we have the following classes: Car
, AutomaticCar
, Transmission
, AutomaticTransmission
. Can you arrange these classes into the following class diagram?