Download Understanding Class Modeling: Objects, Classes, and Relationships and more Study notes Printing in PDF only on Docsity!
Class Modeting
A class model captures the static structure of a system by characterizing the objects in the
system, (^) the relationships between the objects, and the attributes and operations (^) for each class
of objects. The class model is the most important of the three models. We emphasize building
a system around objects rather than around functionality, because an object-oriented system
more closely corresponds to the real world and is consequently more resilient with respect
to change. Class models provide an intuitive graphic representation of a system and are valu-
able for communicating with customers.
Chapter 3 discusses (^) basic class modeling concepts (^) that will (^) be used throughout the
book. We define each concept, present the corresponding UML notation, and provide exam-
ples. Some important concepts that we consider are object, class, link, association, general-
ization' and inheritance. You should master the material in this chapter before proceeding in
the book.
3.1 (^) Object and (^) Class Concepts
3.7.7 (^) Objects
The purpose (^) of class (^) modeling is to describe (^) objects. For example, Joe Smith. Simplex com-
pany, process number 7648, and the top window are objects.
Anobiect is a concept, abstraction, or thing with identity that has meaning for an appli-
cation. Objects often appear as proper nouns or speciflc references in problem descriptions
and discussions with users. Some objects have real-world counterparts(Albert Einstein aad
the General Electric company), while others are conceptual entities (simulation run L234 and
the formula for solving a quadratic equation). Still others (binary tree 634 and the array
bound to variable a) are introduced for implementation reasons and have no correspondence
to physical reality. The choice of objects depends onjudgment and the nature of a problern;
there can be many correct representations.
21
22 Chapter^3 /^ Class Modeling
All objects have identity and are distinguishable. Two^ apples^ with^ the^ same^ color,^ shape,
and texture are^ still^ individual^ apples;^ a^ person can^ eat^ one and then^ eat^ the other.^ Similarly,
identical twins are two^ distinct^ persons, even^ though they may^ look^ the^ same.^ The term
identity means that objects^ are^ distinguished by^ their^ inherent^ existence and^ not by descrip-
tive properties that they may^ have.
3.7.2 Closses
An object is an instance-or occulrence-of^ a class.^ A^ class describes^ a^ group^ of^ objects
with the same properties (attributes), behavior (operations),^ kinds^ of^ relationships, and^ se-
mantics. Person,^ compqny,^ process,^ and^ window^ are^ all^ classes.^ Each^ person has name and
birthdate and^ may^ work^ at^ a^ job.^ Each process has^ an^ owner,^ priority,^ and^ list^ of required re-
sources. Classes often^ appear^ as^ common nouns^ and^ noun^ phrases^ in^ problem descriptions
and discussions with users.
Objects in a class have the^ same^ attributes^ and^ forms of^ behavior.^ Most^ objects derive
their individuality from differences in their attribute^ values and speciflc^ relationships^ to^ other
objects. However, objects^ with^ identical^ attribute values^ and^ relationships^ are^ possible. The
cnlice of classes depends on the^ nature^ and scope^ of^ an^ application^ and^ is^ a^ matter^ ofjudg-
ment.
The objects in a class share^ a^ common^ semantic purpose, above and beyond the^ require-
ment of common attributes^ and^ behavior. For example,^ a^ barn^ and^ a^ horse^ may both^ have^ a
cost and an age. If^ barn^ and^ horse were regarded^ as^ purely flnancial^ assets,^ they^ could belong
to the^ same class.^ If^ the developer^ took into^ consideration that^ a^ person paints^ a^ barn^ and
feeds a^ horse,^ they would^ be^ modeled^ as^ distinct^ classes.^ The^ interpretation^ of^ semantics de-
pends on the^ purpose^ of^ each^ application^ and^ is^ a^ matter of^ judgment'
Each obiect;'knows" its^ class.^ Most^ OO^ progfamming^ languages can^ determine^ an^ ob-
ject's class at run time. An object's class is^ an^ implicit^ property^ of^ the^ object.
If objects are the focus of modeling, why bother^ with^ classes?^ 'fhe^ notion^ of^ absfraction
is at^ the^ heart^ of^ the matter.^ By^ grouping^ objects^ into^ classes,^ we abstract^ a^ problem. Abstrac-
tion gives^ modeling its power^ and^ ability^ to generalize^ from^ a^ few speciflc^ cases^ to^ a^ host^ of
similar cases. Common definitions^ (such^ as^ class name and^ attribute^ names)^ are^ stored once
per class rather than once per instance.^ You^ can^ write^ operations^ once^ for^ each class,^ so^ that
all the objects^ in^ the^ class^ benefit^ from^ code reuse.^ For example,^ all^ ellipsps^ share^ the^ same
procedures to draw them, compute their^ areas,^ and test^ for^ intersection^ with^ a^ line;^ polygons
would have a^ separate^ set^ ofprocedures.^ Even^ special^ cases,^ such^ as^ circles^ and^ squares,^ can use the general procedures,^ though more efficient^ procedures^ are^ possible.
3.7.3 Class Diagram^s
We began this^ chapter^ by^ discussing^ some^ basic^ modeling^ concepts,^ specifically obiect^ and
class.Wehave described^ these concepts^ with^ examples^ and prose.^ This^ approach^ is^ vague
and insufficient for^ dealing^ with^ the^ complexity^ of^ applications. We need^ a means^ for^ ex-
pressing models that is coherent, precise, and^ easy^ to^ formulate.^ There^ are^ two kinds of mod-
els of structure---class diagrams^ and^ object diagrams.
Chapter 3 /^ Class Modeling
Do not confuse values^ with^ objects.^ An^ attribute^ should describe values, not objects.^ Un-
like objects, values lack^ identity.^ For example,^ all^ occurrences^ of^ the^ integer^ "17"^ are^ indis-
tinguisirable, as are^ all^ occulrences of^ the^ string^ 'oCanada."^ The country^ Canada^ is^ an^ object,
whose name attibtte has the^ value "Canada" (the^ string)'
Figure 3.2^ shows^ modeling notation.^ Class Person has^ attributes name^ and^ birthdate'
Namelsa string andbirthdateii^ a^ date. One^ object in^ class^ Personhas^ the value "Joe^ Smith"
for name and^ the^ vafue"2l^ October 1983" for birthdate. Another object^ has^ the value^
"Mary
Sharp" for name and the^ value^ "16 March^ 1950"^ for^ birthdate'
MarySharp:Person
name='lMary sharp" birthdate=1 6 March 1 950
Y
Clnss with Attributes
Person name: string birthdate: date homeTelephoneNumber:string
Correct
Figure 3.3 Object identifiers.^ Do not^ list^ object^ identifiers;^ they^ are^ implicit^ in^ models.
Do not confuse internal identiflers^ with^ real-world^ attributes.^ Internal identifiers^ are
purely an implementation convenience and have^ no application^ meaning.^ In^ contrast,^ tax
p*y"i rrrrrU"i license plate number, and telephone number^ are^ not internal identifiers^ be-
cause they have^ meaning^ in^ the^ real^ world.^ Rather they^ are^ legitimate attributes'
Person name: string birthdate: date
JoeSmith:Person
name="Joe Smith" birthdate=21 October 1 983
Figure 3.2^ Attributes^ and values. Attributes^ elaborate^ classes.
The UML notation lists attributes in the^ second^ compartment of^ the^ class^ box. Optional
details, such as type and^ default^ value,^ may^ follow^ each attribute.^ A^ colon^ precedes the^ type'
An equal sign^ piecedes^ the default value.^ Our^ convention^ is^ to^ show the attribute name^
in
,"gular tace,^ teit^ align^ the name^ in^ the^ box,^ and use^ a^ lowercase^ letter^ for^ the^ first^ letter'
You may also^ include^ attribute^ values^ in^ the^ second^ compaftment^ of^ object boxes' The
notation is to list^ each^ attribute^ name^ followed^ by^ an^ equal sign^ and^ the value' We^ also^ left
align attribute^ values and use^ regular type face'
Some implementation^ media^ require that^ an^ object^ have^ a^ unique identifier.^ These^ iden-
tiflers are impllcit^ in^ a^ class^ model-you^ need^ not^ and should^ not^ list^ them^ explicitly'^ Figure
3.3 emphasizes the^ point.^ Most^ OO^ languages^ automatically^ generate^ identifiers^ with which
to reference^ objects.You^ can also^ readily^ define them^ for^ databases.^ Identiflers^ ale^ a^ comput-
er artifact and have^ no^ intrinsic^ meaning.
Objects with^ Values
3.1 Object and (^) Class Concepts
3.7.5 (^) Operations (^) o;nd Metll'lods
An operati.on is a function or procedure that may be applied to or by objects in a class. Hire,
fire, and^ payDividend^ are^ operations^ on class company. open, close, hide, and, redisplay are
operations on class window. All objects in a class share the same operations.
Each operation has atargetobject as an implicit argument. The Lehavior of the operation
depends on the class of its target. An object "knows" its class, and hence the right implemen-
tation of the operation.
The same operation may apply to many different classes. Such an operation ispolymor-
phic; that is, the same operation takes on different forms in different classes. A method is
the implementation of an operation for a class. For example, the class File may have an op-
eration print You could implement different methods to print ASCfI files, print binary filei,
and print digitized picture files. All these methods logically perform the same task-printing
a file; thus you may refer to them by the generic operationprin/. However, a different piece
of code may implement each method.
An operation may have arguments in addition to its target object. Such arguments may
be placeholders for values, or for other objects. The'choice of a method depends entirely on
the class of the target object (^) and not on any object arguments (^) that an operation (^) may frave. 1,t
few OO languages, notably CLOS, permit the choice of method to depend on any number of
a-rguments, but such generality leads to considerable semantic complexity; which we shall
not explore.)
When an operation has methods on several classes, it is important that the methods all
have the sarcrc signature-the number and types of arguments and the type of result value.
For examptre, print shotld nothave fileName as an argument for one method and, filepointer
for another. The behavior of all methods for (^) an operation should have (^) a consistent intent. It
is best to avoid using the same name for two operations that are semantically different, even
if they apply to distinct sets of classes. (^) For example, it would (^) be unwise to use (^) the name
invert to describe both a matrix inversion and tuming a geometric figure upside-down. In a
large project,^ some form of name scoping may be necessary to accommodate accidental
name clashes, but it is best to avoid any possibility of confusion.
In Figure 3.4,the class Person has attributes name and birthdate and operation s change-
Job and changeAddress. Name, birthdate, changeJob, and changeAddress are features of
Person. Feature is a generic word for either an attribute or operation. Similarly, File has a
print opetation. GeometricObject has move, select, and rotate operations. Move has argu-
mentdelta, whichis aVector;selecthasoneargumentp,whichisof type Pointandreturns
a Booleani arrd rotate has argument angle, which is an input of type float with a default value
of 0.0.
The UML notation is to list operations in the third compartment of the class box. Our
convention is to list the operation name in regular face, left align the name in the box, and
use a lowercase letter for the first letter. Optional details, such as an argument list and result
type, may follow each operation name. Parentheses enclose an argument list; commas sepa-
rate the arguments. A colon precedes the result type. An empty argument list in parentheses
shows explicitly that there are no arguments; otherwise you cannot draw conclusions. We do
not list operations for objects, because they do not vary among objects of the same class.
3.2 Link and Association (^) Concepts
3.2 (^) Link and (^) Association (^) Concepts
Links and associations (^) are the means (^) for establishing relationships (^) among objects and classes.
3.2.7 (^) Links and. (^) Associations
Alink is a physical or conceptual connection among objects. For example, Joe Smith Works-
For Simplex company. Most links relate two objects, but some links reiate three or more ob-
jects. This chapter discusses only binary associations; Chapter 4 discusses n-ary
associations. (^) Mathematically, (^) we define a link as a tuple-that (^) is, a list of (^) objects. A link i;
an instance of an association.
A.nassociation is a description of a group of links with common structure and common
semantics. For example, a person WorksFor a company. The links of an association connect
objects from the same classes. An association describes a set of potential links in the same
way that a class describes a set ofpotential objects. Links and associations often appear as
verbs in problem statements.
Figure 3.7 is an excerpt of a model for a financial application. Stock brokerage firms
need to perform tasks such as recording ownership of various stocks, tracking dividends,
alerting customers to changes in the market, and computing margin requirements. The top
portion of the figure shows a class diagram and the bottom shows an object diagram
Classdiagram (^) i tlname (^) I (^) lname I
Object diagram
Figure 3.7 Many'to-many association. An association describes a set of potential
links in the same way that a class describes a set of potential objects.
28 Chapter^3 /^ Class Modeling
In the class diagram,^ a^ person^ may own^ stock^ in^ zero or more companies;^ a^ company
may have multiple persons^ owning^ its^ stock.^ The object diagram^ shows^ some^ examples.
John, Mary, and Sue own stock in^ the GE company.^ Sue and^ Alice^ own^ stock^ in^ the^ IBM
company. Jeff does not own stock in any company^ and^ thus^ has^ no^ link.^ The asterisk is^ a^ mul-
tiplicity symbol. Multiplicity^ specifles the^ number^ of^ instances^ of^ one class^ that may relate
to a single instance of another class and^ is^ discussed^ in^ the^ next^ section.
The UML notation for a link is a line^ between^ objects;^ a^ line may^ consist^ of^ several^ line
segments. If the link^ has^ a^ name,^ it^ is underlined. For example,^ Johl^ owns stock^ in^ the GE
company. An association connects related^ classes and^ is also denoted^ by^ a^ line^ (with^ possibly
multiple line segments). For example, persons^ own^ stock^ in^ companies.^ Our convention^ is^ to
show link^ and association^ names^ in italics^ and^ to confine^ line^ segments^ to^ a^ rectilinear^ grid.
It is good to arrange the classes^ in^ an association^ to^ read^ from left-to-right, ifpossible.
The association name^ is optional,^ if^ the^ model is unambiguous.^ Ambiguity^ arises^ when
a model has multiple associations among^ the^ same classes Qterson works^ for company and
person owns stock in company).When there^ are^ multiple^ associations,^ you^ must use associ-
ation names or association^ end names^ (Section 3.2.3) to^ resolve^ the ambiguity.
Associations are inherently^ bidirectional.^ The^ name^ of^ a^ binary^ association^ usually
reads in a particular direction, but^ the^ binary^ association^ can^ be^ traversed^ in^ either direction.
For example,WorksFor connects a person^ to^ a^ company.^ The^ inverse^ of^ WorksFor^ could^ be
called Employs,^ and^ it^ connects^ a^ company to^ a^ person.^ In reality, both directions of traversal
are equally meaningful and^ refer^ to the^ same^ underlying^ association;^ it^ is^ only^ the^ names^ that
establish a direction.
Developers often implement associations in programming^ languages^ as^ references^ from
one object to another. Areference is an attribute^ in^ one^ object that refers to another object.
For example, a data structure for Person might contain an^ attribute employer^ that^ refers to^ a
Company object, andaCompanyobjectmightcontainanattribute^ employees^ thatrefersto
asetof Person objects. Implementing^ associations^ as^ references^ is^ perfectly^ acceptable,^ but
you should not model associations this way.
A link is a relationship among objects. Modeling^ a^ link^ as a^ reference^ disguises the^ fact
that the link is not part of^ either^ object^ by itself,^ but depends^ on^ both of^ them together.^ A^ com-
pany is not part^ of a person, and^ a^ person is^ not part of^ a^ company.^ Furthermore, using^ a^ pair
of matched references, such as the reference^ from Personto Company^ andthe reference^ from
Company to^ a^ set^ of^ Persons,^ hides the fact that the^ forward^ and^ inverse^ references depend
on each other. Therefore,^ you^ should model^ all^ connections among^ classes^ as^ associations,
even in designs for^ programs.
The OO literature emphasizes encapsulation,^ that^ implementation details^ should^ be^ kept
private to a class, and we certainly agree with^ this.^ Associations^ are^ important, precisely^ be-
cause they break encapsulation.^ Associations^ cannot be^ private to^ a^ class, because they^ tran-
scend classes. Failure to^ treat^ associations^ on^ an^ equal^ footing^ with^ classes^ can^ lead to
programs containing hidden assumptions^ and dependencies.^ Such^ programs^ are^ difficult^ to
extend and the classes are difficult to^ reuse.
Although modeling treats associations as^ bidirectional, you^ do not^ have^ to^ implement
them in both directions. You^ can^ readily implement^ associations^ as^ references^ if^ they^ are^ only
30 Chapter 3 / Class Modeling
Figure 3.9 Zero-or-one multiplicity. It may be optional whether^ an^ object
s involved in an association.
Do not confuse "multiplicity"^ with "cardinality."^ Multiplicity^ is^ a^ c'onstrain^ on the size
of a collection; cardinality is^ the^ count^ of^ elements that^ are^ actually^ in^ a^ collection.^ There-
fore, multiplicity is a constraint on the cardinality.
A multiplicity of "many"^ specifies that^ an^ object may be^ associated^ with^ multiple^ ob-
jects. However, for each association there is at most one link between a^ given^ pair of objects
(except (^) for bags and sequences, see Section 3.2.5). As Figure 3.10 and Figure 3.11^ show,^ if
you want two links between the same objects, you must^ have^ two^ associations.
Figure 3.10 Association vs.^ Iink.^ A^ pair^ of^ objects can be^ instantiated^ at
most once per association (except^ for^ bags and sequences).
aLink lanA:A aB:B^ I l-@
Figure 3.11 Association^ vs.^ link.^ You^ can use^ multiple^ associations^ to
model multiple links^ between the^ same^ objects.
Multiplicity depends on assumptions^ and^ how you define^ the^ boundaries^ of^ a^ problem.
Vague requirements often make^ multiplicity^ uncertain. Do not^ worry^ excessively^ about^ mul-
tiplicity early in software development. First determine^ classes^ and associations, then^ decide
on multiplicity. If you omit multiplicity notation from a diagram,^ multiplicity^ is considered
to be unspecified.
Multiplicity often exposes hidden assumptions^ built into^ a^ model. For example,^ is^ the
WorksFor association between Person and^ Company one-to-many or many-to-many?^ It^ de-
pends on the context. A tax collection application would permit^ a person to^ work^ for multiple
companies. On the^ other^ hand, the member records^ for^ an^ auto^ workers'union^ may consider
second jobs^ irrelevant. Class diagrams^ help to^ elicit^ these^ hidden^ assumptions,^ making them
visible and subject to scrutiny.
The most important multiplicity distinction is^ between "one"^ and^ "many."^ Underesti-
mating multiplicity can restrict the flexibility of an application. For example, many^ programs
ffi
Class diagram Object^ diagram
Class diagram Object diagram
3.2 Link and Association Concepts
cannot accommodate persons with multiple phone numbers. On the other hand, overestimat-
ing multiplicity imposes overhead and requires the application to supply additional informa-
tion to distinguish among the members of a "many" set. In a true hierarchical organization,
for example, it is better to represent "boss" with a multiplicity of "zero or one," rather tban
allow for nonexistent matrix management.
3.2.3 Association End.Illames
Our discussion of multiplicity implicitly referred to the ends of associations. For example, a
one-to-many association has two ends-an end with a multiplicity of "one" and an end with
a multiplicity of "many."^ The notion of an association end is an important concept in the
UML. You can not only assign a multiplicity to an association end, but you can give it a name
as well. (Chapter 4 discusses additional properties of association ends.)
Association end names often appear as nouns in problem descriptions. As Figure 3.
shows, a name appears next to the association end. In the figure Person and Company par-
ticipate in association WorksFor.A person is an employee with respect to a company; a com-
pany is an employer with respect to a person. Use of association end names is optional, but
it is often easier and less confusing to assign association end names instead of, or in addition
to, association names.
31
emolovee emolover i Person ffii
company
I
employer Simolex Simblex Unit'ed Widgets
employee Joe Doe Marv Brown Jea6 Smith
Figure 3.12 Association end names. Each end of an association can have a name.
Association end names are especially convenient for traversing associations, because
you can treat each one as a pseudo attribute. Each end of a binary association refers to an
object or set of objects associated with a source object. From the point of view of the source
object, traversal ofthe association is an operation that yields related objects. Association end
names provide a means of traversing an association, without explicitly mentioning the asso-
ciation. Section 3.5 talks further about traversing class models.
Association end names are necessary for associations between two objects of the same
class. For example, in Figure 3.13 container ard contents distinguish the two usages of Di-
rectory in the self-association. A directory may contain many lesser directories and may op-
tionally be contained itself. Association end names can also distinguish multiple associatioirs
between the same pair of classes. In Figure 3.13 each directory has exactly one user who is
an owner and many users who are authorized to use the (^) directory. When there is only a single
association between a pair of distinct classes, the names of the classes often suffice, and you
may omit association end names.
3.2 Link and Association Concepts
I (^) visibleon *l^ I
Bigure 3.15 Ordering the objects for an association end. Ordering sometimes
occurs for o'many"^ multiplicity.
3.2.5 Bags o;nd. *quences
Ordinarily a binary association has at most one link for a pair of objects. However, you can
permit multiple links for a pair of objects by annotating an association end with {bag} or {se-
quence]. Abag is a collection of elements with duplicates allowed. Asequence is an ordered
collection of elements with duplicates allowed. In Figure 3.16 an itinerary is a sequence of
airports and the same airport can be visited more than once. Like the {ordered} indication,
{bag} and^ {sequence} are^ permitted^ only for binary^ associations.
{seouencer
Figure 3.16 An example of a sequence. An itinerary may visit multiple airports,
so you should luse^ {seqwence} andnot {ordered}.
UML1 did not permit multiple links for a pair of objects. Some modelers misunderstood
this restriction with ordered association ends and constructed incorrect models, assuming
that there could be multiple links. With IJML} the modeler's intent is now clear. If you spec-
ify (^) {bag} or (^) {sequence}, then there can be multiple links for a pair of objects. If you omit
these annotations, then the association has at most one link for a pair of objects.
Note that the {ordered} and the {sequence}annotations are the same, except that the first
disallows duplicates and the other allows them. A sequence association is an ordered bag,
while an ordered association is an ordered set.
3.2.6 .Lssociation (^) Classes
Just as you^ can describe the objects of a class with attribut'es, so too you can describe the
links of an association with attributes. The UML represents such information with an asso-
ciation class. An association c/ass is an association that is also a class. Like the links of an
association, the instances of an association class derive identity from instances of the con-
stituent classes. Like a class, an association class can have attributes and operations and par-
ticipate in associations. You can find association classes by looking for adverbs in a problem
statement or by abstracting known values.
In Figure (^) 3.17, accessPermission is an attribute of AccessibleBy. The sample data at the
bottom of the figure shows the value for each link. The UML notation for an association class
is a box (a^ class box) attached to the association by a dashed line.
34 Chapter 3 / Class Modeling
AccessibleBy
accessPermission
/etc/termcap read^ John Doe /etc/termcab read-write Marv Brown /usr/doe/.lolin read-write Joh6 Doe
Figure 3.17 An association class. The links of an association can have attributes.
Many-to-qrany associations provide a compelling rationale for association classes. At-
tributes for such associations unmistakably belong to the link and canlnot be ascribed to ei-
ther object. In Figure 3.1'7, accessPermission is a joint^ property of File and User and cannot
be attached to either File or User alone without losing information.
Figure 3.18 presents attributes for two one-to-many associations. Each person working
for a company receives a salary and has a job title. The boss evaluates the performance of
each worker. Attributes may also occur for one-to-one associations.
Manages
performanceRating
Figure 3.18 Association classes. Attributes may also occur for one-to-many
and one-to-one associations.
Figure 3.19 shows how it is possible to fold attributes for one-to-one and one-to-many
associations into the class opposite a"orte" end. This is not possible for many-to-many as-
sociations. As a rule, you should not fold such attributes into a class because the multiplicity
of the association might change. Either form in Figure 3.19 canexpress a one-to-many asso-
ciation. However, only the association class form (^) remains correct if the multiplicity of WorksFor is changed to many-to-many.
Figure 3.20 shows an association class participating in an association. Users may be au-
thorized on many workstations. Each authorization carries a priority and access privileges.
A user has a home directory for each authorized workstation, but several workstations and
users can share the same home directory. Association classes are an important aspect of class
modeling because they let you specify identity and navigation paths precisely.
36 Chapter 3 / Class Modeling
Do not confuse an association class with an association that has been promoted^ to a
class. Figure 3.21 highlights the difference. The association class has only one occuffence
for each pairing of Person arrd Company.In contrast there can be any number of occurrences
of a Purchase for each Person and Company. Each purchase is^ distinct and^ has^ its own quan-
tity, date, and cost.
3.2.7 (^) Qualified Associatiotrs
A quaffied association is an association in which an attribute called the qualificr drsambig-
uates the objects for a "many"^ association end.^ It^ is possible to deflne qualifiers^ for^ one-to-
many and many-to-many associations. A qualifier^ selects among the target objects,^ reducing
the effective multiplicity, from "many" to "one." Qualified associations with a target multi-
plicity of "one" or "zero-or-one" specify a precise path for finding the target object from the
source object.
Figure 3.22 illustrates the most coflrmon use^ of^ a^ qualifler-^ for^ associations^ with^ one-
to-many multiplicity. A bank services multiple accounts. An account belongs to^ a single
bank. Within the context of a bank, the account number specifies a unique account. Bank and
Account are classes and accountNumber is the qualifier. Qualification reduces the effective
multiplicity of this association from one-to-many to one-to-one.
Figure 3.22 Qualified association. Qualification increases the precision^ of a model.
Both models are acceptable, but the qualifled model adds information. The qualified
model adds a multiplicity constraint, that the combination of a bank and an account number
yields at most one account. The qualified model conveys the significance of account number
in traversing the model, as methods will reflect. You^ first find^ the^ bank^ and^ then specifl,^ the
account number to flnd the account.
The notation for a qualifler is a small box on the end of the association line near^ the
source class. The qualifier box may grow out of any side (top, bottom, left, right) of the
source class. The source class plus the^ qualifler yields^ the^ target class.^ In^ Figure 3.22 Bank
+ accountNumber yields an Account, therefore accountNumber is^ listed^ in^ a^ box contiguous
to Bank.
Figure 3.23 provides another example of qualification. A stock exchange lists many
companies. However, a stock exchange lists^ only^ one^ company^ with^ a^ given^ ticker^ symbol.
A company may be listed on many stock exchanges, possibly under different^ symbols.^ (We
are presuming this is true. If every stock had a single ticker symbol that was invariant^ across
exchanges, we would make tickerSymbol an attribute of Company.)
Quaffied Not^ quaffied
3.3 Generalization and lnheritance
' =\r+^ .--_,^ _\a
Quaffied^ Not^ quaffied
Figure 3.23 Qualified association. Qualification also facilitates traversal of class models.
3.3 Generalization and Inheritance
3.3.7 Definition
Generalization is the relationship between^ a^ class^ (the^ superclass) and one or more varia-
tions of the class (thesrDclasses). Generalization organizes classes by their similarities and
differences, structuring the description of objects. The superclass holds common attributes,
operations, and associations; the subclasses add speciflc attributes, operations, and associa-
tions. Each subclass is^ said to^ inherit^ the features^ of its^ superclass.^ Generalization^ is^ some-
times called the "is-a" relationship, because each instance ofa subclass is an instance ofthe
superclass as well.
Simple generalization organizes classes into a hierarchy; each subclass has a single im-
mediate superclass. (Chapter 4 discusses a more complex form of generalization in which a
subclass may^ have^ multiple^ immediate^ superclasses.) There^ can be multiple^ levels of gener-
alizations.
Figure 3.24 shows several examples of generalization for equipment. Each piece of
equipment is^ a pump,^ heat exchanger. or tank. There^ are several kinds of pumps: centrifugal,
diaphragm, andplunger. There are several kinds oftanks: spherical, pressurized,^ and floating
roof. The fact that the tank generalization symbol is drawn below the pump generalization
symbol is not significant. Several objects are displayed at the bottom of the'figure. Each ob-
ject inherits features from one class at each level ofthe generalization. Thus P101 embodies
the features of equipment, pump, and diaphagm pump. E302 has the properties of equip-
ment and heat exchanger.
A large hollow arrowhead denotes generalization. The arrowhead points to the super-
class. You may directly connect the superclass to each subclass, but we normally prefer to
group subclasses as a tree. For convenience, you can rotate the triangle and place it on any
side, but if possible you should draw the Superclass on top and the subclasses on the bottom.
The curly braces denote a UML comment, indicating that there are additional subclasses that
the diagram does not show.
3.3 Generalizationandlnheritance
class. Each subclass not only inherits all the features ofits ancestors but adds its own specific
features as well. For example, Pump adds attributes suctionPressure, dischargePressure, and
flowRate, which^ other kinds^ of^ equipment^ do^ not^ share.
Figure 3.25 shows classes of geometric figures. This example has more of a program-
ming flavor and emphasizes inheritance of operations. Move, select, rotate, and. display are
operations that all subclasses inherit. Scale apphes to one-dimensional and two-dimensional
figures. Fill (^) applies only to two-dimensional figures.
Figure 3.25 Inheritance for graphic figures. Each subclass inherits the
attributes, operations, and associations of its superclasses.
The word written next to the generalization line rn the diagram-4imensioruality-is a
generalization set name. Agenerakmtian set narne is an enumerated attribute that indicates
which aspect of an object is being abstracted by a particular generalization. You should gen-
eralize only one aspect at a time. For example, the means of propulsion (wind, fuel, animal,
gravity) and the operating environment (land, air, water, outer space; are two aspects for
classVehicle. Generalization set values are inherently in one-to-one correspondence with the
subclasses of a generalization. The generalization set name is optional.
color centerPosition penThickness penType
dimensionality
40 Chapter 3 / Class Modeling
Do not nest subclasses too deeply. Deeply nested subclasses can be difficult to under-
stand, much^ like^ deeply^ nested^ blocks^ of^ code^ in^ a^ procedural language.^ Often,^ with^ some
careful thought and a little restructuring, you^ can reduce the depth^ of^ an^ overextended^ inher-
itance hierarchy. In practice, whether or not a subclass is "too^ deeply nested"^ depends upon
judgment and the particular details of a problem. The following guidelines may help: An in-
heritance hierarchy that is two or three levels deep is certainly acceptable; ten levels deep is
probably excessive; five or six levels may or may not be proper.
3.3.2 Use oJ @n.ero.lizo;tion
Generalization has three purposes, one of which is support for polymorphism.^ You^ can^ call
an operation at the superclass level, and the OO language compiler automatically resolves
the call to the method that matches^ the^ calling object's^ class.^ Polymorphism^ increases the
flexibility of software-you add a new subclass and^ automatically inherit^ superclass behav-
ior. Furthermore, the new subclass does not disrupt existing code. Contrast the OO situation
with procedural^ code,^ where^ addition of^ a^ new^ type^ can cause^ a^ ripple of^ changes.
The second purpose^ of generalization^ is^ to^ structure the description^ of^ objects. When
you use generalization, you are making a conceptual statement-you are forming a taxono-
my and organizing objects on the basis of their similarities and differences. This is^ much
more profound than modeling each class individually and in isolation from other classes.
The third purpose is to enable reuse of code-you can inherit code within your applica-
tion as well as from^ past^ work^ (such^ as^ a class^ library).^ Reuse^ is^ more productive than re-
peatedly writing code from scratch. Generalization also lets you adjust the code, where
necessary, to get the precise desired behavior. Reuse is an important motivator for^ inherit-
ance, but the benefits are often oversold as Chapter 14 explains. The terms generalization, specialization, and inheritance all refer to aspects of the same
idea. Generalization and specialization concera^ a^ relationship^ among^ classes^ and take^ oppo-
site perspectives, viewed from the superclass or from the subclasses. The^ word generaliza-
tion deives from the fact that the superclass generalizes the subclasses. Specializationrefers
to the fact that the subclasses refine^ or^ specialize the^ superclas^ s.'Inheritance^ is the^ mecha-
nism for sharing attri.butes, operations, and associations via the generalization/specialization
relationship. In practice, there is little danger of confusion between the terms.
3.3.3 Ooeniding Features
A subclass may override a superclass feature by defining a feature with the same name. The
overriding feature (the^ subclass feature) reflnes^ and replaces the^ overridden feature (the^ su-
perclass (^) feature). There are several reasons why you may wish to override a feature: to spec-
ify behavior that depends on the subclass, to tighten the speciflcation of a feature, or to
improve performance. For example, in Figure 3.25, each leaf subclass must implement dis-
play, even though Figure defines it. Class Circle improves performance by overriding oper-
ation rotate to be a null operation.
You may override methods and default values of attributes. You should never override
the signature, or form, of a feature. An override should preserve attribute type, number and