Java Reference
In-Depth Information
Suppose, for example, that a Salary class extends an Employee class. We dis-
cussed in Chapter 6, “Understanding Inheritance,” how this was a good
design because a salaried employee is an employee. From the point of view of
polymorphism, a Salary object is an Employee object. This means a Salary
object can be treated as an Employee object.
A child object being treated as a parent class type has the following benefits:
Using a parent class reference to a child object.
■■
Using polymorphic parameters and return values.
■■
Creating heterogeneous collections of objects, where not all objects in
the collection are of the same type.
■■
We will now discuss each of these benefits of polymorphism in detail.
Using Parent Class References to Child Objects
A child object can be referenced using a parent class reference. This is the most
fundamental use of polymorphism because using a parent class reference to
refer to a child object is what allows you to take advantage of the benefits of
polymorphism.
To demonstrate polymorphism in action, I will use the following Employee
and Salary classes, which represent classes used to pay employees of a com-
pany. (I am going to use this employee example throughout this chapter.)
Notice in Listing 8.1 that the Employee class has three fields: name, address,
and number; one constructor; a mailCheck() method; the toString() method;
and various accessor methods. There are no fields in the Employee class used
to represent the employee's pay because we decided in Chapter 6 that this data
should appear in the child classes.
public class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println(“Constructing an Employee”);
this.name = name;
this.address = address;
this.number = number;
Listing 8.1
The Employee class extends Object implicitly.
Search WWH ::




Custom Search