Java Reference
In-Depth Information
Display 7.3 contains the definition of a class for hourly employees. An hourly
employee is an employee, so we define the class
HourlyEmployee
to be a
derived
class of the class
Employee
. A
derived class
is a class defined by adding instance
variables and methods to an existing class. The existing class that the derived class is
built upon is called the
base class
. In our example,
Employee
is the base class and
HourlyEmployee
is the derived class. As you can see in Display 7.3, the way we
indicate that
HourlyEmployee
is a derived class of
Employee
is by including the phrase
extends Employee
on the first line of the class definition, like so:
derived class
base class
extends
public class
HourlyEmployee
extends
Employee
A derived class is also called a
subclass
, in which case the base class is usually called a
superclass
. However, we prefer to use the terms
derived class
and
base class
.
When you define a derived class, you give only the added instance variables and the
added methods. For example, the class
HourlyEmployee
has all the instance variables
and all the methods of the class
Employee
, but you do not mention them in the
definition of
HourlyEmployee
. Every object of the class
HourlyEmployee
has instance
variables called
name
and
hireDate
, but you do not specify the instance variable
name
or
the instance variable
hireDate
in the definition of the class
HourlyEmployee
. The class
HourlyEmployee
(or any other derived class) is said to
inherit
the instance variables and
methods of the base class that it extends. For this reason, the topic of derived classes is
called
inheritance
.
Just as it inherits the instance variables of the class
Employee
, the class
HourlyEmployee
inherits all the methods from the class
Employee
. So, the class
HourlyEmployee
inherits the methods
getName
,
subclass and
superclass
inheritance
getHireDate
,
setName
,
and
setHireDate
, from the class
Employee
.
For example, suppose you create a new object of the class
HourlyEmployee
as
follows:
HourlyEmployee joe =
new
HourlyEmployee();
Then, the name of the object
joe
can be changed using the method
setName
, which
the class
HourlyEmployee
inherited from the class
Employee
. The inherited method
setName
is used just like any other method; for example,
joe.setName("Josephine");
A small demonstration of this is given in Display 7.4.
Display 7.5 contains the definition of the class
SalariedEmployee
, which is also
derived from the class
Employee
. The class
SalariedEmployee
inherits all the instance
variables and methods of the class
Employee
. Inheritance allows you to reuse code, such
as the code in the class
Employee
, without needing to literally copy the code into the
definitions of the derived classes, such as
HourlyEmployee
and
SalariedEmployee.
VideoNote
Inheritance
Walkthrough