Java Reference
In-Depth Information
Similarly, if lines 56 and 60 used superclass variable
currentEmployee
to invoke sub-
class-only methods
getBaseSalary
and
setBaseSalary
, we'd receive “
cannot
find
symbol
” compilation errors at these lines. Attempting to invoke subclass-only methods via
a superclass variable is
not
allowed—even though lines 56 and 60 execute only if
instanceof
in line 49 returns
true
to indicate that
currentEmployee
holds a reference to
a
BasePlusCommissionEmployee
object. Using a superclass
Employee
variable, we can
invoke only methods found in class
Employee
—
earnings
,
toString
and
Employee
's
get
and
set
methods.
Software Engineering Observation 10.5
Although the actual method that's called depends on the runtime type of the object to
which a variable refers, a variable can be used to invoke only those methods that are
members of that variable's type, which the compiler verifies.
Subclass Variables
Now that you've seen a complete application that processes diverse subclass objects
polymor-
phically
, we summarize what you can and cannot do with superclass and subclass objects
and variables. Although a subclass object also
is a
superclass object, the two classes are nev-
ertheless different. As discussed previously, subclass objects can be treated as objects of their
superclass. But because the subclass can have additional subclass-only members, assigning
a superclass reference to a subclass variable is not allowed without an
explicit cast
—such an
assignment would leave the subclass members undefined for the superclass object.
We've discussed three proper ways to assign superclass and subclass references to vari-
ables of superclass and subclass types:
1.
Assigning a superclass reference to a superclass variable is straightforward.
2.
Assigning a subclass reference to a subclass variable is straightforward.
3.
Assigning a subclass reference to a superclass variable is safe, because the subclass
object
is an
object of its superclass. However, the superclass variable can be used
to refer
only
to superclass members. If this code refers to subclass-only members
through the superclass variable, the compiler reports errors.
We saw in Sections 6.3 and 6.10 that variables can be declared
final
to indicate that they
cannot be modified
after
they're initialized—such variables represent constant values. It's
also possible to declare methods, method parameters and classes with the
final
modifier.
Final Methods Cannot Be Overridden
A
final
method
in a superclass
cannot
be overridden in a subclass—this guarantees that
the
final
method implementation will be used by all direct and indirect subclasses in the
hierarchy. Methods that are declared
private
are implicitly
final
, because it's not possi-
ble to override them in a subclass. Methods that are declared
static
are also implicitly
fi-
nal
. A
final
method's declaration can never change, so all subclasses use the same method