Unit 3 · OOP Concepts

3.4.2Self-check and practice

Self-check questions

Write your answers first, then open the answers to check them.

  1. Define encapsulation in one sentence.
  2. What is the purpose of a setter if the attribute could be public?
  3. How do you make an attribute read-only?
Show answers
  1. 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.

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

  3. Make it private, set it in the constructor, and provide a getter but no setter. Marking it final as well makes the compiler enforce it.

Practice exercises

  1. Encapsulate a Student class: private name and marks, a setter that rejects marks outside 0 to 100.
    Hint
    Java
    public void setMarks(int marks) {
        if (marks >= 0 && marks <= 100) {
            this.marks = marks;
        } else {
            System.out.println("Marks must be 0 to 100");
        }
    }
  2. Create an Employee class with salary that cannot be set to a negative value and can only be increased by a giveRaise(percent) method.
  3. Write tests (normal, boundary, invalid) for your setters.