(^346) | Inheritance, Polymorphism, and Scope
7.6 Implementing a Derived Class
Given the CRC card design for a subclass and its superclass, you can determine what you must
include in the subclass to implement its responsibilities. You may find that you simply need
to change the operation of an inherited method, which means that you override or hide it
with a new version. Because a derived class doesn’t inherit any constructors, it will proba-
bly need one or more new constructors. We often implement new constructors by calling the
old ones to do much of the work, and then adding a few statements to take care of initializ-
ing any new fields that we’ve added. In some cases, you may find it necessary to change the
internal representation of the subclass.
After you have designed the subclass interface and its internal representation, you im-
plement it by writing the necessary field and method declarations within a class declaration
that extendsthe superclass. Here are the steps in the form of a checklist:
1.Study the interfaces of the superclass and the subclass, identifying the members
that are inherited.
2.Determine whether the internal representation must change in the subclass.
3.Provide constructors as needed.
4.Add fields and methods to those that are inherited, as necessary.
5.Hide any inherited fields or class methods that you wish to replace.
6.Override any instance methods that you wish to replace.
We have already seen how to read an existing class hierarchy to determine what is
inherited by a subclass. When we are creating a new hierarchy, we start from a set of
CRC cards. During the enactment of the scenarios, it may become clear that certain re-
sponsibilities arepublic,private, or package-level in their access requirements; this fact
should be written on the cards. As we’ve noted, a CRC card design rarely results in apro-
tectedresponsibility.
As we design the internal representation for a class, we may also notice that certain
fields need an access level other than package. For example, we might define somepublic
class constants. Armed with this information, we can list the members that a subclass in-
herits.
Next, we reconsider the choice of internal representation given the responsibilities of the
subclass. Unless we have a good reason for making the representation different from the su-
perclass, it should remain the same. Thus we begin with the inherited representation and
look for any omissions. We can easily add any extra fields needed.
Sometimes an inherited field is inappropriate for the subclass. Perhaps the superclass
uses an intfield for part of its representation, and the purpose of the subclass is to extend
its range by using long. Then we must hide the inherited field in the subclass.
Once we have the interface and internal representation, we can begin to implement the
constructors. Java has some special rules regarding constructors in derived classes that we
examine next.