Java Reference
In-Depth Information
1.11.1. Invoking Methods of the Superclass
To make
Pixel
do the correct "clear" behavior, we provide a new im-
plementation of
clear
that first invokes its superclass's
clear
using the
super
reference. The
super
reference is a lot like the
this
reference de-
scribed previously except that
super
references things from the super-
class, whereas
this
references things from the current object.
The invocation
super.clear()
looks to the superclass to execute
clear
as
it would for an object of the superclassnamely,
Point
. After invoking
su-
per.clear()
to clear out the
Point
part of the object, we add new func-
tionality to set
color
to a reasonable empty value. We choose
null
, a
reference to no object.
What would happen had we not invoked
super.clear()
in the previous
example?
Pixel
's
clear
method would set
color
to its
null
value, but the
x
and
y
variables that
Pixel
inherited from
Point
would not be set to any
"cleared" values. Not clearing all the values of a
Pixel
object, including
its
Point
parts, is probably a bug.
When you invoke
super.
method
()
, the runtime system looks back up the
inheritance hierarchy to the first superclass that contains the required
method
. If
Point
didn't have a
clear
method, for example, the runtime
system would look at
Point
's superclass for such a method and invoke
that, and so on.
For all other references, invoking a method uses the actual class of the
object,
not the type of the object
reference.
Here is an example:
Point point = new Pixel();
point.clear(); // uses Pixel's clear()
In this example,
Pixel
's version of
clear
is invoked even though the vari-
able that holds the
Pixel
is declared as a
Point
reference. But if we in-
voke
super.clear()
inside one of
Pixel
's methods, that invocation will use
the
Point
class's implementation of the
clear
method.