Java
Setter
Learn mutator methods and validation with setX.
Setter method
To change the value of a private field, you write a setter method. A setter returns void, takes a parameter and is named with a set prefix. Validation can be done inside the setter; invalid values are rejected.
Example: void setAge(int a) { if (a >= 0) age = a; }. Here the setter rejects negative age values. You cannot write age = -5 directly; even if setAge(-5) is called, the value is not assigned. This ensures the data always stays valid. A setter controls data changes from a single point; this is the power of encapsulation.
Validation with setters
A setter offers the opportunity to validate during data changes. The parameter value is checked; if valid, it is assigned to the field, otherwise it is rejected or a default is used. This preserves the class's invariants.
Example: In a Temperature class, the setCelsius(double c) method can reject values below absolute zero: if (c >= -273.15) celsius = c;. This validation ensures the class always stays physically meaningful. The validation logic stays in one place inside the setter; it is not repeated elsewhere in the class. Without encapsulation, this check would need to be done separately at every assignment.
Exercise Add a setter to Student
Define a class Student. Add a private int age field. Write a public int getAge() getter returning age. Write a void setAge(int a) setter; its body runs if (a >= 0 && a <= 150) age = a;. In main create a Student instance, call setAge(20) and print the result of getAge().
Show example solution
class Student {
private int age;
public int getAge() {
return age;
}
void setAge(int a) {
if (a >= 0 && a <= 150) age = a;
}
public static void main(String[] args) {
Student s = new Student();
s.setAge(20);
System.out.println(s.getAge());
}
}
Test yourself
-
What does validation inside a setter do?
- It prevents invalid values
- It speeds up the method
- It deletes the field
- It hides the method
Show answer
It prevents invalid values — Validation inside a setter prevents invalid values from being assigned.
-
Complete the setter validation
void setAge(int a) {
if (a >= 0) ____ = a;
}
Show answer
void setAge(int a) {
if (a >= 0) age = a;
}
-
Match the setter parts
- void
- Return type
- setAge
- Method name
- int a
- Parameter
- if (a >= 0)
- Validation
Next lesson: Package-private