Java Reference
In-Depth Information
associate professor
assistant professor
staff member
secretary
technician
janitor
alumni
The indentation used above is used to describe the
is-a
relation. For exam-
ple, the three lines indented underneath the entry
staff member
indicate that a sec-
retary
is a
staff member, a technician
is a
staff member, and a janitor
is a
staff
member. Also, a student
is a
university member, a professor
is a
faculty member
is
a university member, and so on.
The
is-a
relation is fundamental in dealing with subclasses: if
c
is a
b
, then
when constructing classes, we make
C
a subclass of class
B
. For example, sup-
pose we write a class for each of the objects in this hierarchy. Then, class
UniversityMember
has no superclass (except
Object
). Class
Student
is a sub-
class of
UniversityMember
,
Professor
is a subclass of
FacultyMember
, and so
on. So, we have a general guideline:
Make a class
B
a subclass of class
C
if each instance of
B
is a
C
.
Commonality of behavior
We explain why we structure classes and subclasses according to the
is-a
relation, using students as an example. The three kinds of students share common
behavior, which will be reflected in the instance methods in class
Student
. For
example, all students have a name, so there will probably be a method to get this
name. And they pay tuition. Method
getName
may be defined in class
Student
,
but
all
university members have names, so the method is better defined in
UniversityMember
and inherited in class
Student
. Only students pay tuition, so
method
payTuition
will be defined in class
Student
.
Thus, we have the following principle:
Subclass principle
: Structure classes so that behavior that is
common to several classes can be defined in a superclass of those
classes.
Sometimes, we insert new classes to make better use of this guideline. For
example, all faculty and staff get pay, so we may decide to insert a new class,
Employee
, so that method
getPay
may be placed in it.
Search WWH ::
Custom Search