Programming and Problem Solving with Java

(やまだぃちぅ) #1
7.6 Implementing a Derived Class | 349

To summarize, overloading allows us to add new versions of a name that can coexist in
a single context, while hiding and overriding provide a way to replace a name with a new dec-
laration in a different context.


Accessing Overridden and Hidden Methods and Fields


Using the keyword superfollowed by a parameter list refers to the constructor in the super-
class with the same signature. Keep in mind that you have to use superor the name of the
superclass in only two cases:


 When you are accessing a method or field that has been overridden or hidden
 When you are accessing a superclass constructor

Otherwise, the name has been inherited and you can refer to it directly.
Here are some examples of using super:


super(); // Call to the default constructor of the superclass
someInt = super.someInt; // Reference to a hidden field in the superclass
super.classMethod(); // Call to a hidden class method in the superclass
SuperClassName.classMethod(); // Another way to call the same hidden method
super.instanceMethod(); // Call to an overridden instance method in the superclass


A Concrete Example


In the example used to present the CRC card technique in Chapter 6, the filtered list of
classes included a business phone number. What distinguishes a business number from a
home number is the presence of an extension in the business number. Let’s extend the class
Phoneto include an extension number. We need to add a field in BusinessPhoneto hold the ex-
tension. Should we change the methods asDigitsand asStringto include the extension? Yes;
let’s do so. Here, then, is the CRC card for BusinessPhone:


Class Name: BusinessPhone Superclass: Phone Subclasses:


Responsibilities Collaborations

Create itself (area code, number, extension) Phone


Know its extension None


return int


asDigits Phone


return long


asStrin gPhone


returnString


.


.


.

Free download pdf