Programming and Problem Solving with Java

(やまだぃちぅ) #1
7.4 Derived Class Syntax | 337

Polymorphism


Let’s take a closer look at the mechanism that allowsgetUIClassIDto have two different imple-
mentations. When it is applied to aJTextField, it has one implementation; when applied to a
JComponent, it has another. In object-oriented terms, we say thatgetUIClassIDispoly-
morphic. That is, it has multiple forms. Java decides which form to use depending on
the class of the object.
Together with inheritance and encapsulation, polymorphism gives us the
ability to flexibly implement a hierarchy of objects. We use polymorphism to sub-
stitute different implementations of a responsibility as required by variations in
the internal representation of classes at different levels of the hierarchy. For ex-
ample,Addressmight represent a ZIP code as a single string, but then we might
redefine its representation in the CompanyAddressclass so that the four-digit extension is kept
separately. Thus, the “Know ZIP code” responsibility would be implemented differently in
CompanyAddressthan in Address.


7.4 Derived Class Syntax


The declaration of a derived class looks very much like the declaration of any other class. Here
is the syntax template for a declaring class:


The only difference between this template and the one in Chapter 2 is that we’ve added
the optional extendsclause that allows us to indicate the superclass from which our new class
is derived. Here’s an example declaration:


public classBusinessPhone extendsPhone
{
// Declare new data fields and methods as needed
}


This new class inherits all of the fields and methods of Phone(including anything Phonehas
inherited) and then adds some of its own. Is that all there is to implementing a derived class?
In terms of syntax, yes. But in terms of semantics, there is more we need to know.
In Chapters 2 and 3, we learned how to create individual classes that are fully encapsu-
lated. With inheritance and polymorphism, we are beginning to create related sets of classes.


Class-Modifiers... extends Classname

Class-Declaration...

{

class Identifier

}

Polymorphic operation An
operation that has multiple
meanings depending on the class
of object to which it is bound
Free download pdf