Java Reference
In-Depth Information
7.3
Programming with Inheritance
The devil is in the details.
COMMON SAYING
In the previous section, we described the basic idea and details of derived classes.
In this section, we continue that discussion and go on to cover some more subtle
points about derived classes. In the process, we also discuss the class
Object
, which
is an ancestor class of all Java classes, and we describe a better way to define an
equals
method.
TIP: Static Variables Are Inherited
Static variables in a base class are inherited by any derived classes. The modifiers
public
,
private
, and
protected
, and package access have the same meaning for
static variables as they do for instance variables.
■
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
defi ned earlier has an instance variable
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 keyword
super
as if it were a calling object.
super
relationship