(^352) | Inheritance, Polymorphism, and Scope
Here are the results of file DrPhoneOut:
Look carefully at this driver. The method equals, as defined in Phone, is applied to objects
of both Phoneand BusinessPhone. The methods knowAreaCodeand knowDigits, as defined in
Phone, are applied to objects of both Phoneand BusinessPhone. The overridden methods asDigits
and asStringare applied to objects of both Phoneand BusinessPhone, with the system deter-
mining which method is appropriate.
Before we move on to the input and output of objects, we would like to introduce one
more technique. In Chapter 6, we mentioned that it is sometimes useful to create construc-
tors that take an existing instance and use its contents to build a new instance. We use these
copy constructorsto illustrate the difference between shallow and deep copying of objects.
7.7 Copy Constructors
One way to simplify the creation of a new instance of an immutable object (one with no
transformer methods) from an old instance is to provide a constructor that takes an exist-
ing object as a parameter. It may also have other parameters that provide values to substi-
tute in creating the new object. Here’s an example of the heading and documentation for such
a constructor:
publicSavingsAccount(SavingsAccount oldAcct, String address)
// oldAcct must contain valid account information.
// A SavingsAccount object is created with its contents
// equal to those of the old account except that
// the address is set equal to the address parameter.