Practice Encapsulation
Implementing Encapsulation
Let’s update the classes from the previous exercises to incorporate encapsulation.
General Implementation Tips:
- Private Fields: Use the
privatekeyword to make fields private, restricting direct access from outside the class. - Getters and Setters: Write a
gettermethod to retrieve each field’s value and asettermethod to modify it. - Validation: Consider adding validation in setter methods to ensure the data is valid (e.g., GPA should be between 0.0 and 10.0).
Exercise 1: Student Class
Scenario: Update the Student class to implement encapsulation.
- Original Fields:
String studentIdString namedouble gpa
Instructions:
- Update the
Studentclass to make the fields private. - Add getter and setter methods for each field.
- In the tester class, update the code to use the setters to assign values and the getters to retrieve and print the values.
Exercise 2: Book Class
Scenario: Update the Book class to implement encapsulation.
- Original Fields:
String isbnString titleString author
Instructions:
- Update the
Bookclass to make the fields private. - Add getter and setter methods for each field.
- In the tester class, update the code to use the setters to assign values and the getters to retrieve and print the book details.
Exercise 3: Car Class
Scenario: Update the Car class to implement encapsulation.
- Original Fields:
String licensePlateString makeString model
Instructions:
- Update the
Carclass to make the fields private. - Add getter and setter methods for each field.
- In the tester class, update the code to use the setters to assign values and the getters to retrieve and print the car information.
Exercise 4: Movie Class
Scenario: Update the Movie class to implement encapsulation.
- Original Fields:
String movieIdString titleint durationMinutes
Instructions:
- Update the
Movieclass to make the fields private. - Add getter and setter methods for each field.
- In the tester class, update the code to use the setters to assign values and the getters to retrieve and print the movie details.
Exercise 5: Employee Class
Scenario: Update the Employee class to implement encapsulation.
- Original Fields:
String employeeIdString namedouble salary
Instructions:
- Update the
Employeeclass to make the fields private. - Add getter and setter methods for each field.
- In the tester class, update the code to use the setters to assign values and the getters to retrieve and print the employee’s information.
Next Topic: Constructors
Go to Constructors to learn more with examples.