Java Reference
In-Depth Information
Adding the following line to the constructor computes the value of the field:
this
.
r
=
Math
.
sqrt
(
cx
*
cx
+
cy
*
cy
);
// Pythagorean theorem
But wait; this new field
r
has the same name as the radius field
r
in the
Circle
superclass. When this happens, we say that the field
r
of
PlaneCircle
hides
the field
r
of
Circle
. (This is a contrived example, of course: the new field should really be
called
distanceFromOrigin
).
In code that you write, you should avoid declaring fields with
names that hide superclass fields. It is almost always a sign of
bad code.
With this new definition of
PlaneCircle
, the expressions
r
and
this.r
both refer to
the field of
PlaneCircle
. How, then, can we refer to the field
r
of
Circle
that holds
the radius of the circle? A special syntax for this uses the
super
keyword:
r
// Refers to the PlaneCircle field
this
.
r
// Refers to the PlaneCircle field
super
.
r
// Refers to the Circle field
Another way to refer to a hidden field is to cast
this
(or any instance of the class) to
the appropriate superclass and then access the field:
((
Circle
)
this
).
r
// Refers to field r of the Circle class
This casting technique is particularly useful when you need to refer to a hidden field
defined in a class that is not the immediate superclass. Suppose, for example, that
classes
A
,
B
, and
C
all define a field named
x
and that
C
is a subclass of
B
, which is a
subclass of
A
. Then, in the methods of class
C
, you can refer to these different fields
as follows:
x
// Field x in class C
this
.
x
// Field x in class C
super
.
x
// Field x in class B
((
B
)
this
).
x
// Field x in class B
((
A
)
this
).
x
// Field x in class A
super
.
super
.
x
// Illegal; does not refer to x in class A
You cannot refer to a hidden field
x
in the superclass of a
superclass with
super.super.x
. This is not legal syntax.
Similarly, if you have an instance
c
of class
C
, you can refer to the three fields named
x
like this: