/
08 - Inheritance - Exercise

08 - Inheritance - Exercise

Overview

The objective of this exercise is to define a new class by extending an existing class. Then make use of some classes in the Java standard library.

Task 1 - Create a Manager class

  1. In the project from our previous exercise called EmployeeManagement, create a new class called Manager.

  2. Modify the definition so that Manager is a subclass of Employee.

  3. Provide a constructor for this class and call the superclass constructor to initialise the variables for name and age.

  4. In EmployeeApplication, create a third object, but this time a manager, with suitable constructor arguments. Print out the details, just as you did for the Employees.

  5. Refactor the code in EmployeeApplication. Instead of the three separate declarations, create an array of three Employee references, initialise two of them to Employee and one to Manager for the array elements.

  6. Use a loop to print out the details for each object in the array.

Task 2 - Add functionality to Manager class

  1. Edit the Manager class to provide an instance variable called manages of type Employee[]. This variable should of course be private. In the constructor, initialise this giving the array a capacity of 100. Provide another instance variable to keep track of the last free position in the array.

  2. Define an instance method addEmployee(), taking an Employee reference as a parameter and returning void. Implement this method to add the employee object to the array, using the last free position variable. Do not forget to increment it afterwards!

  3. Define another method getEmployeeNames(), with no arguments, but returning String. Implement this method to loop around the collection, concatenating the names from each Employee. Finally return this String.

  4. Enhance EmployeeApplication, so that you have a manger who manages the other two employees!

  5. In Employee, override the toString() method to return the information about the employee. Use it in the loop in your main method!

  6. In Manager, implement the toString() method as well, but don't forget to incorporate the names of the employees the manager manages.

  7. As a stretch, try to create a manger who manages other mangers!

Related content