Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^332) | Inheritance, Polymorphism, and Scope
Figure 7.2 shows the relation-
ships among these classes.Address,
the most general form, appears at the
top of its hierarchy, just below Object,
which is at the top of any hierarchy.
The ability of a programming lan-
guage to support the creation of su-
perclasses and subclasses is known
as inheritance. Each subclass inherits
the responsibilities that are defined
by its superclass, including all of the
responsibilities that the superclass
has inherited. In addition, subclasses
are assignment-compatible with the
superclasses above them in the hierarchy. That is, we can assign a Work Address
object to a Work Address variable, a Company Address variable, an Address vari-
able, or an Object variable.
Periodically in the CRC card design process, it is useful to look for similarities
among the cards and decide whether a superclass should be created. Inheritance
is also used when we start to create a new class and realize that it is just a varia-
tion of an existing class. In this situation, there is no need to define an entirely new
Class Name: Home Address Superclass: Address Subclasses:
Responsibilities: Create Collaborations
Create itself (name, street, apartment,
city, state, ZIP code)
Name
Know its apartment
return String
None
Know its street
return String
None
Class Name: Box AddressSuperclass: Company Address Subclasses:
Responsibilities Collaborations
Create itself (name, company, box, city,
state, ZIP code)
Name
Know its Box
return String
None
Object
Address
Home Address Company Address
Work Address Box Address
Figure 7.2 Address Object Hierarchy
Inheritance A mechanism by
which one class acquires the
properties—the data fields and
methods—of another class

Free download pdf