Chapter 7

Programming with Abstract Classes and Interfaces

In this lesson you learn about so-called abstract classes, and then you build a complete application that will illustrate how to design and implement programs with abstract classes and interfaces. You also learn about the notion of polymorphism.

Abstract Classes

If a class is declared abstract it can’t be instantiated. The keyword abstract has to be placed in the declaration of a class. The abstract class may have abstract method(s). The question is “Who needs a class that can’t be instantiated?”

It’s easiest to answer this question by showing you how to use abstract classes while designing an application. While previous lessons ended with assignments, this lesson will start with one.

Assignment

A company has employees and contractors. Design the classes without using interfaces to represent the people who work for this company. The classes should have the following methods:

changeAddress() 
promote() 
giveDayOff() 
increasePay() 

A one-time promotion means giving one day off and raising the salary by a specified percentage. The method increasePay() should raise the yearly salary for employees and increase the hourly rate for contractors.

Solution with an Abstract Class

Since increasePay() has to be implemented differently for Employee and Contractor, let’s declare it as abstract. The class Person will also have three concrete methods. The fact that the abstract class Person cannot be instantiated forces us, the ...

Get Java® Programming 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.