Polymorphism with classes

Polymorphism with classes comes into the picture when a class inherits another class and both the base and the derived classes define methods with the same method sig- nature (the same method name and method parameters). As discussed in the previ- ous section, an object can also be referred to using a reference variable of its base class. In this case, depending on the type of the object used to execute a method, the Java runtime executes the method defined in the base or derived class.

We’ll start with the Employee class, which is not quite sure about what must be done to start work on a project (execute method startProjectWork). Hence, the method startProjectWork is defined as an abstract method, and the class Employee is defined as an abstract class, as follows:

The class Programmer extends the class Employee, which essentially means that it has access to the method reachOffice defined in Employee. Programmer must also implement the abstract method startProjectWork, inherited from Employee. How do you think a Programmer will typically start work on a programming project? Most probably, the Programmer will define classes and unit test them. This behavior is con- tained in the definition of the class Programmer, which implements the method start- ProjectWork, as follows:

We’re fortunate to have another special type of Employee, a Manager, who knows how to start work on a project. How do you think a Manager will typically start work on a programming project? Most probably, the Manager will meet with the customers, define a project schedule, and assign work to the team members. Here’s the defini- tion of the class Manager that extends the class Employee and implements the method startProjectWork:

Problem:

Last updated