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
In the project from our previous exercise called
EmployeeManagement
, create a new class calledManager
.Modify the definition so that Manager is a subclass of
Employee
.Provide a constructor for this class and call the superclass constructor to initialise the variables for name and age.
In
EmployeeApplication
, create a third object, but this time a manager, with suitable constructor arguments. Print out the details, just as you did for theEmployee
s.Refactor the code in
EmployeeApplication
. Instead of the three separate declarations, create an array of threeEmployee
references, initialise two of them toEmployee
and one toManager
for the array elements.Use a loop to print out the details for each object in the array.
Task 2 - Add functionality to Manager class
Edit the
Manager
class to provide an instance variable called manages of typeEmployee[]
. This variable should of course beprivate
. 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.Define an instance method
addEmployee()
, taking anEmployee
reference as a parameter and returningvoid
. Implement this method to add the employee object to the array, using the last free position variable. Do not forget to increment it afterwards!Define another method
getEmployeeNames()
, with no arguments, but returningString
. Implement this method to loop around the collection, concatenating the names from eachEmployee
. Finally return thisString
.Enhance
EmployeeApplication
, so that you have a manger who manages the other two employees!In
Employee
, override thetoString()
method to return the information about the employee. Use it in the loop in your main method!In
Manager
, implement thetoString()
method as well, but don't forget to incorporate the names of the employees the manager manages.As a stretch, try to create a manger who manages other mangers!