Java Reference
In-Depth Information
Abstract Classes
In Chapter 7 , we defined a class named
Employee
and two of its derived classes,
HourlyEmployee
and
SalariedEmployee
. Display 8.6 repeats the details of these
class definitions, which we will use in this discussion.
Suppose that when we define the class
Employee
, we know that we are going to
frequently compare employees to see if they have the same pay. We might add the
following method to the class
Employee
:
public boolean
samePay(Employee other)
{
return
(
this
.getPay() == other.getPay());
}
There is, however, one problem with adding the method
samePay
to the class
Employee
: The method
samePay
includes an invocation of the method
getPay
, and
the class
Employee
has no
getPay
method. Moreover, there is no reasonable definition
we might give for a
getPay
method so that we could add it to the class
Employee
.
The only instance variables in the class
Employee
give an employee's name and hire
date, but give no information about pay. To see how we should proceed, let's compare
objects of the class
Employee
to employees in the real world.
Every real-world employee does have some pay because every real-world employee
is either an hourly employee or a salaried employee, and the two derived classes
HourlyEmployee
and
SalariedEmployee
each have a
getPay
method. The problem is
that we do not know how to define the
getPay
method until we know if the employee is
an hourly or salaried. We would like to postpone the definition of the
getPay
method and
give it only in each derived class of the
Employee
class. We would like to simply add a note
to the
Employee
class that says: “There will be a method
getPay
for each
Employee
but
we do not yet know how it is defined.” Java lets us do exactly what we want. The official
Java equivalent of our promissory note about the method
getPay
is to make
getPay
an
abstract method
. An abstract method has a heading just like an ordinary method, but
no method body. The syntax rules of Java require the modifier
abstract
and require a
semicolon in place of the missing method body, as illustrated by the following:
abstract
method
public abstract double
getPay();