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.
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.
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 ...