Java Reference
In-Depth Information
public void clear() {
super.clear();
color = null;
}
}
Pixel extends both the data and behavior of its Point superclass. Pixel
extends the data by adding a field named color . Pixel also extends the
behavior of Point by overriding Point 's clear method.
Pixel objects can be used by any code designed to work with Point ob-
jects. If a method expects a parameter of type Point , you can hand it a
Pixel object and it just works. All the Point code can be used by anyone
with a Pixel in hand. This feature is known as polymorphism a single ob-
ject like Pixel can have many ( poly- ) forms ( -morph ) and can be used
as both a Pixel object and a Point object.
Pixel 's behavior extends Point 's behavior. Extended behavior can be en-
tirely new (adding color in this example) or can be a restriction on old
behavior that follows all the original requirements. An example of re-
stricted behavior might be Pixel objects that live inside some kind of
Screen object, restricting x and y to the dimensions of the screen. If the
original Point class did not forbid restrictions for coordinates, a class with
restricted range would not violate the original class's behavior.
An extended class often overrides the behavior of its superclass by
providing new implementations of one or more of the inherited methods.
To do this the extended class defines a method with the same signature
and return type as a method in the superclass. In the Pixel example,
we override clear to obtain the proper behavior that Pixel requires. The
clear that Pixel inherited from Point knows only about Point 's fields but
obviously can't know about the new color field declared in the Pixel sub-
class.
 
Search WWH ::




Custom Search