Java Reference
In-Depth Information
class
B
extends
A
{
int
i
;
// This field hides i in A
int
f
()
{
// This method overrides f() in A
i
=
super
.
i
+
1
;
// It can retrieve A.i like this
return
super
.
f
()
+
i
;
// It can invoke A.f() like this
}
}
Recall that when you use
super
to refer to a hidden field, it is the same as casting
this
to the superclass type and accessing the field through that. Using
super
to
invoke an overridden method, however, is not the same as casting the
this
refer‐
ence. In other words, in the previous code, the expression
super.f()
is not the
same as
((A)this).f()
.
When the interpreter invokes an instance method with the
super
syntax, a modified
form of virtual method lookup is performed. The first step, as in regular virtual
method lookup, is to determine the actual class of the object through which the
method is invoked. Normally, the runtime search for an appropriate method defini‐
tion would begin with this class. When a method is invoked with the
super
syntax,
however, the search begins at the superclass of the class. If the superclass imple‐
ments the method directly, that version of the method is invoked. If the superclass
inherits the method, the inherited version of the method is invoked.
Note that the
super
keyword invokes the most immediately overridden version of a
method. Suppose class
A
has a subclass
B
that has a subclass
C
and that all three
classes define the same method
f()
. The method
C.f()
can invoke the method
B.f()
, which it overrides directly, with
super.f()
. But there is no way for
C.f()
to
invoke
A.f()
directly:
super.super.f()
is not legal Java syntax. Of course, if
C.f()
invokes
B.f()
, it is reasonable to suppose that
B.f()
might also invoke
A.f()
.
This kind of chaining is relatively common when working with overridden meth‐
ods: it is a way of augmenting the behavior of a method without replacing the
method entirely.
Don't confuse the use of
super
to invoke an overridden
method with the
super()
method call used in a constructor to
invoke a superclass constructor. Although they both use the
same keyword, these are two entirely different syntaxes. In
particular, you can use
super
to invoke an overridden method
anywhere in the overriding class while you can use
super()
only to invoke a superclass constructor as the very first state‐
ment of a constructor.
It is also important to remember that
super
can be used only to invoke an overrid‐
den method from within the class that overrides it. Given a reference to an
Ellipse
object
e
, there is no way for a program that uses
e
to invoke the
area()
method
defined by the
Circle
class on
e
.