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
to be a
derived
class of
HourlyEmployee
the 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
. A
derived
class
derived class
Employee
base class
. In our example,
is the base class and
is
base class
Employee
HourlyEmployee
the derived class. As you can see in Display 7.3, the way we indicate that
Hourly-
is a derived class of
is by including the phrase
Employee
Employee
extends Employee
on the first line of the class definition, like so:
extends
public class HourlyEmployee extends Employee
A derived class is also called a
subclass
, in which case the base class is usually called
subclass and
superclass
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
has all the instance variables
HourlyEmployee
and all the methods of the class
, but you do not mention them in the defini-
Employee
tion of
. Every object of the class
has instance vari-
HourlyEmployee
HourlyEmployee
ables called
and
, but you do not specify the instance variable
or
name
hireDate
name
the instance variable
in the definition of the class
. The class
hireDate
HourlyEmployee
the instance variables
and methods of the base class that it extends. For this reason, the topic of derived
classes is called
(or any other derived class) is said to
inherit
HourlyEmployee
.
Just as it inherits the instance variables of the class
inheritance
inheritance
, the class
Employee
Hourly-
inherits all the methods from the class
. So, the class
Employee
Employee
Hourly-
inherits the methods
,
,
, and
,
Employee
getName
getHireDate
setName
setHireDate
from the class
.
For example, suppose you create a new object of the class
Employee
as follows:
HourlyEmployee
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.
Search WWH ::




Custom Search