Java Reference
In-Depth Information
public void
upDatePayRate(
double
increment)
{
//...
}
Then the following statement will generate a compiler error:
newEmployee.upDatePayRate(25);
//causes compiler error
The reason for this error is that, because
newEmployee
is a reference variable of type
Employee
, it can point to an object of the
class
FullTimeEmployee
or an object of the
class
PartTimeEmployee
, but it can only guarantee that the object it points to can use
the methods
wages
and
department
. However, if we know that
newEmployee
points
to an object of the
class
FullTimeEmployee
, then using an appropriate cast operator,
we can call the method
upDatePayRate
as follows:
((FullTimeEmployee)newEmployee).upDatePayRate(25);
You can expand or extend the hierarchy as needed to accommodate additional kinds of
employees. For example, a board member might be another kind of employee, expanding
the hierarchy. Or, there might be two kinds of full-time employees: those who receive a
fixed salary and those who are paid by the hour. Java provides the flexibility to accom-
modate the expansion and extension, and to represent these kinds of class relationships.
You can also use an
interface
name to declare a parameter to a method. In this case,
any reference variable of any class that implements that interface can be passed as an
(actual) parameter to that method.
Composition is another way to relate two classes. In composition (aggregation), one
or more members of a class are objects of one or more other classes. Composition can be
viewed as a ''has-a'' relation; for example, ''every person has a date of birth.''
The
class
Person
, as defined in Chapter 8, Example 8-8, stores a person's first name
and last name. Suppose we want to keep track of additional information, such as a
personal ID and date of birth. Because every person has a personal ID and a date of
birth, we can define a new
class
PersonalInfo
, in which one of the members is an
object of type
Person
. We can declare additional members to store the personal ID and
date of birth for the
class
PersonalInfo
.
First, we define another
class
,
Date
, to store only a person's date of birth, and then
construct the
class
PersonalInfo
from the
class
es
Person
and
Date
. This way, we
can demonstrate how to define a new class using two classes.
To define the
class
Date
, we need three instance variables to store the month, day
number, and year. Some of the operations that need to be performed on a date are to set
the date and to print the date. The following statements define the
class
Date
:
Search WWH ::
Custom Search