Java Reference
In-Depth Information
refers to. More specifically, it is legal for a superclass variable to refer to an object of
its subclass. The following is a legal assignment statement:
Employee ed = new Lawyer();
When we were studying the primitive types, we saw cases in which a variable of
one type could store a value of another type (for example, an
int
value can be stored
in a
double
variable). In the case of primitive values, Java converts variables from
one type to another:
int
values are automatically converted to
double
s when they
are assigned.
When a subclass object is stored in a superclass variable, no such conversion
occurs. The object referred to by
ed
really is a
Lawyer
object, not an
Employee
object. If we call methods on it, it will behave like a
Lawyer
object. For example, the
call of
ed.getVacationForm()
returns
"
pink
"
, which is the
Lawyer
's behavior, not
the
Employee
's.
This ability for variables to refer to subclass objects allows us to write flexible
code that can interact with many types of objects in the same way. For example, we
can write a method that accepts an
Employee
as a parameter, returns an
Employee
,
or creates an array of
Employee
objects. In any of these cases, we can substitute a
Secretary
,
Lawyer
, or other subclass object of
Employee
, and the code will still
work. Even more importantly, code will actually behave differently depending on
which type of object is used, because each subclass overrides and changes some of
the behavior from the superclass. This is polymorphism at work.
Here is an example test file that uses
Employee
objects polymorphically as param-
eters to a static method:
1 // Demonstrates polymorphism by passing many types of employees
2 // as parameters to the same method.
3
public class
EmployeeMain3 {
4
public static void
main(String[] args) {
5 Employee edna =
new
Employee();
6 Lawyer lucy =
new
Lawyer();
7 Secretary stan =
new
Secretary();
8 LegalSecretary leo =
new
LegalSecretary();
9
10 printInfo(edna);
11 printInfo(lucy);
12 printInfo(stan);
13 printInfo(leo);
14 }
15
16 // Prints information about any kind of employee.
17
public static void
printInfo(Employee e) {
18 System.out.print(e.getHours() + ", ");
Search WWH ::
Custom Search