Lesson 7Programming with Abstract Classes and Interfaces
In this lesson you learn about abstract classes, and then you build a complete application that illustrates 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. Previous lessons ended with assignments, but this lesson starts 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
Classes Employee
and Contractor
should have some common functionality, but because increasePay()
has to be implemented differently for Employee
and Contractor
, let’s declare a superclass Person
for them with an abstract (not implemented) method increasePay()
. The class ...
Get Java Programming 24-Hour Trainer, 2nd Edition 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.