/
02 - OOP Intro - Exercise 2

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

  1. Open your Employee.java file you created in the previous exercise.

  2. Set the visibility of all the attributes to private.

  3. Set the visibility to all the methods to public.

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

  1. Open the EmployeeApplication.java file and fix all the errors.

  2. You should see that you are no longer allowed to set the employee object’s values directly.

  3. You would need to use your new constructor as the default ‘no-arg’ constructor is no longer available.

Task 3 - Create an instance method

  1. In the Employee class, create an instance variable int age. Include the age property into your constructor. Create an instance method called incAge().

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

  3. Back in EmployeeApplication.java and within the main method, after displaying the initial details of each employee, call the incAge() method and redisplay the employee's details. Make sure your method works correctly.

  4. Still in the main method, enclose your call to incAge() in a for loop and verify that the age does not increase beyond 65.

 

Related content