Java Reference
In-Depth Information
The Benefits of Using Abstract Classes
and Methods
Declaring the Employee class as abstract has several important benefits in terms of the
overall design of our program to pay employees. First, no Employee objects can be instan-
tiated. This makes sense in our application because no employee of the company proba-
bly wants to be just an Employee object anyway. The Employee class does not contain any
information about how that employee is paid.
In addition, if we used a heterogeneous collection of Employee references to manage
the company's employees, every object in the data structure needs to be of type
Employee. This is fine for Salary and Hourly employees because these two classes extend
Employee. Suppose, however, that a new Contractor class is needed. If the Contractor
objects want to appear in the company's data structure, they need to be of type Employee.
This forces the Contractor class to extend the Employee class.
This leads to another benefit of abstraction, in which a method can be declared abstract.
If Contractor extends Employee, Contractor must override the abstract computePay()
method, thereby forcing the Contractor class to contain a computePay() method. That fits
in perfectly with our design because we want the Contractor class to have a computePay()
method anyway. Forcing behavior on a class is a typical and widely used OOP design.
(Interfaces, discussed in Chapter 10, “Interfaces,” are used extensively for this purpose.)
By using inheritance, abstraction, and polymorphism, the design of our employee
program is now taking advantage of the fundamental benefits of OOP. If a new type
of employee is needed, the class written to represent these new employees has to
extend Employee if it wants to appear in the data structure. Because this new class
must extend Employee, it must contain a computePay() method, which is what we wanted
to accomplish in the first place with this program.
Most importantly, none of the existing classes are affected when a new type of
employee comes along. When the Contractor class is added, the Employee class does not
change; it is merely extended. The Salary and Hourly classes are not affected at all. The
SmartBoss class that pays employees doesn't have to worry about new types of employ-
ees either because virtual methods are used, so the SmartBoss has no problem paying
Contractor objects.
The PayEmployees class in Listing 8.17 uses the SmartBoss class to pay
some Employee objects. What I want you to notice about this example is that
the SmartBoss class discussed earlier does not need any modifications, even
though the Employee class has since been made abstract and we added an
entirely new class named Contractor.
Study the PayEmployees program, which compiles and executes success-
fully, and try to determine its output, which is shown in Figure 8.7.
Search WWH ::




Custom Search