02 - OOP Intro - Exercise 2
Overview
Working with the solution from the previous exercise, we will apply the best encapsulation practices and create constructors for our class.
Task 1 - Encapsulation and Constructors
Open your
Employee.java
file you created in the previous exercise.Set the visibility of all the attributes to
private
.Set the visibility to all the methods to
public
.Create a constructor that would accepts 4 parameters - first name, last name, id and department. Remember that a constructor has the same name as the class (even the capital letter) and does not return anything (not even
void
).
Task 2
Open the
EmployeeApplication.java
file and fix all the errors.You should see that you are no longer allowed to set the employee object’s values directly.
You would need to use your new constructor as the default ‘no-arg’ constructor is no longer available.
Task 3 - Create an instance method
In the Employee class, create an instance variable
int age
. Include the age property into your constructor. Create an instance method calledincAge()
.This method should be
public
and it should increment the employee's age by one. However, if the employee is 65, they should not be allowed to turn 66 as that is the retirement age. Make sure that your employee can't be over 65.Back in
EmployeeApplication.java
and within themain
method, after displaying the initial details of each employee, call theincAge()
method and redisplay the employee's details. Make sure your method works correctly.Still in the
main
method, enclose your call toincAge()
in a for loop and verify that the age does not increase beyond 65.