Java Reference
In-Depth Information
TIP: “is a” Versus “has a”
Early in this chapter, we defined a derived class called
HourlyEmployee
using the class
Employee
as the base class. In such a case, an object of the derived class
HourlyEmployee
is
also an instance of the class
Employee
, or, stated more simply, an
HourlyEmployee
is an
Employee
. This is an example of the “is a” relationship between classes. It is one way to
make a more complex class out of a simpler class.
Another way to make a more complex class out of a simpler class is known as the
“has a” relationship. For example, the class
Employee
defined earlier has an instance vari-
able of the class type
Date
. We express this relationship by saying an
Employee
“has a”
Date
. Using the “has a” relationship to build a class (such as building the class
Employee
by using
Date
as an instance variable) is often called
composition
.
Because the class
HourlyEmployee
inherits the instance variable of type
Date
from
the class
Employee
, it is also correct to say an
HourlyEmployee
“has a”
Date
. Thus, an
HourlyEmployee
is an
Employee
and
has a
Date
.
“is a”
relationship
“has a”
relationship
composition
■
Access to a Redefined Base Method
Suppose you redefine a method so that it has a different definition in the derived class
from what it has in the base class. The definition that was given in the base class is not
completely lost to the derived class objects. However, if you want to invoke the version
of the method given in the base class with an object in the derived class, you need
some way to say, “use the definition of this method as given in the base class (even
though I am an object of the derived class).” The way you say this is to use the key-
word
super
as if it were a calling object.
For example, the method
toString
of the class
HourlyEmployee
(Display 7.3) was
defined as follows:
super
relationship
public
String toString()
//in the derived class HourlyEmployee
{
return
(getName() + " " + getHireDate().toString()
+ "\n$" + wageRate + " per hour for " + hours + " hours");
}
This overrides the following definition of
toString()
that was given in the definition
of the base class
Employee
:
public
String toString()
//in the base class Employee
{
return
(name + " " + hireDate.toString());
}