Java Reference
In-Depth Information
c
.
x
// Field x of class C
((
B
)
c
).
x
// Field x of class B
((
A
)
c
).
x
// Field x of class A
So far, we've been discussing instance fields. Class fields can also be hidden. You can
use the same
super
syntax to refer to the hidden value of the field, but this is never
necessary, as you can always refer to a class field by prepending the name of the
desired class. Suppose, for example, that the implementer of
PlaneCircle
decides
that the
Circle.PI
field does not express to enough decimal places. She can define
her own class field
PI
:
public
static
final
double
PI
=
3.14159265358979323846
;
Now code in
PlaneCircle
can use this more accurate value with the expressions
PI
or
PlaneCircle.PI
. It can also refer to the old, less accurate value with the expres‐
sions
super.PI
and
Circle.PI
. However, the
area()
and
circumference()
meth‐
ods inherited by
PlaneCircle
are defined in the
Circle
class, so they use the value
Circle.PI
, even though that value is hidden now by
PlaneCircle.PI
.
m
g
O
Overriding Superclass Methods
When a class defines an instance method using the same name, return type, and
parameters as a method in its superclass, that method
overrides
the method of the
superclass. When the method is invoked for an object of the class, it is the new defi‐
nition of the method that is called, not the old definition from the superclass.
The return type of the overriding method may be a subclass of
the return type of the original method (instead of being
exactly the same type). This is known as a
covariant return
.
Method overriding is an important and useful technique in object-oriented pro‐
gramming.
PlaneCircle
does not override either of the methods defined by
Circle
,
but suppose we define another subclass of
Circle
, named
Ellipse
.
It is important for
Ellipse
to override the
area()
and
circumference()
methods
of
Circle
in this case, because the formulas used to compute the area and circum‐
ference of a circle do not work for ellipses.
The upcoming discussion of method overriding considers only instance methods.
Class methods behave quite differently, and they cannot be overridden. Just like
fields, class methods can be hidden by a subclass but not overridden. As noted ear‐
lier in this chapter, it is good programming style to always prefix a class method
invocation with the name of the class in which it is defined. If you consider the class
name part of the class method name, the two methods have different names, so
nothing is actually hidden at all.