Java Reference
In-Depth Information
subclass-only methods such as
takeDictation
,
sue
, or
fileLegalBriefs
on the
object that is passed in, even if the actual object might have those methods.
The variable's type can be any type equal or higher in the inheritance hierarchy
compared to the actual object. So we could store a legal secretary in a variable of
type
Secretary
, which would allow us to execute any standard secretary behavior,
including taking dictation:
Secretary steve = new LegalSecretary();
steve.takeDictation("Hello!"); // OK
steve.fileLegalBriefs(); // compiler error
It is legal to cast a variable into a different type of reference in order to make a call
on it. This does not change the type of the object, but it promises the compiler that
the variable really refers to an object of the other type. For example, the following
code works successfully:
Employee ed = new Secretary();
((Secretary) ed).takeDictation("Hello!"); // OK
You can only cast a reference to a compatible type, one above or below it in its
inheritance hierarchy. The preceding code will compile, but it would crash at runtime
if the variable
ed
did not actually refer to an object of type
Secretary
or one of its
subclasses. Casting references will come in handy later in this chapter when we
implement the
equals
method.
Inheritance and polymorphism introduce some complex new mechanics and behavior
into programs. One useful way to get the hang of these mechanics is to perform exer-
cises to interpret the behavior of programs with inheritance. The main goal of these
exercises is to help you understand in detail what happens when a Java program with
inheritance executes.
The
EmployeeMain3
program developed in the previous section serves as a tem-
plate for inheritance questions of the following form: Given a certain hierarchy of
classes, what behavior would result if we created several objects of the different types
and called their various methods on them?
In order to use polymorphism and keep our program compact, we'll store the
objects in an array. In the case of the
Employee
hierarchy, it's legal for an object of
class
Lawyer
,
Secretary
, or any other subclass of
Employee
to reside as an element
of an
Employee[]
.
The following program produces the same output as the
EmployeeMain3
program
from the previous section:
1
public class
EmployeeMain4 {
2
public static void
main(String[] args) {
Search WWH ::
Custom Search