Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.4 Encapsulation — setters and validation

Lesson

Controlled writing: the setter

A setter is a method that changes a private field, giving controlled write access. Because the write goes through a method, the setter can check the value first and reject bad input — something a plain public field could never do. This is a big reason to keep fields private.


Worked example

class Person {
    private int age;

    int getAge() { return age; }

    void setAge(int a) {
        if (a >= 0) {       // validate: no negative ages
            age = a;
        }
    }
}

Person p = new Person();
p.setAge(-5);                    // rejected, age stays 0
System.out.println(p.getAge());  // 0
p.setAge(20);                    // accepted
System.out.println(p.getAge());  // 20

▶ Try it: setAge ignores negative values. Run this, then try other values (negative and positive) and re-run.



What is a setter?


setAge ignores negatives. On a new Person (age starts 0), after setAge(-5) then setAge(20), what is the age?


Why route writes through a setter instead of a public field?


True or false?


Type exactly what this program prints.

class Age {
    private int value;
    int get() {
        return value;
    }
    void set(int v) {
        if (v >= 0) {
            value = v;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Age a = new Age();
        a.set(-3);
        System.out.println(a.get());
        a.set(12);
        System.out.println(a.get());
    }
}