Self-check questions
Write your answers first, then open the answers to check them.
- Define encapsulation in one sentence.
- What is the purpose of a setter if the attribute could be public?
- How do you make an attribute read-only?
Show answers
Encapsulation is bundling an object's data with the methods that use it, and hiding the data so that it can only be read or changed through controlled public methods.
A setter can check the new value and reject invalid ones (for example a negative balance), and it is the one place to change if the rule changes. A public attribute can be set to anything, by any code.
Make it
private, set it in the constructor, and provide a getter but no setter. Marking itfinalas well makes the compiler enforce it.
Practice exercises
- Encapsulate a Student class: private name and marks, a setter that rejects marks outside 0 to 100.
Hint
Javapublic void setMarks(int marks) { if (marks >= 0 && marks <= 100) { this.marks = marks; } else { System.out.println("Marks must be 0 to 100"); } } - Create an Employee class with salary that cannot be set to a negative value and can only be increased by a
giveRaise(percent)method. - Write tests (normal, boundary, invalid) for your setters.