Setter
- Java course
- Intermediate
- Lesson 26/116
- 5 min
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.
Practice 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().
Starter code
// Define the Student class
// Add a private age field, getter and setter
// Add validation in the setterSample 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());
}
}Expected output
20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does validation inside a setter do?
- It prevents invalid values Correct answer
- It speeds up the method
- It deletes the field
- It hides the method
Explanation: Validation inside a setter prevents invalid values from being assigned.
2 Complete the setter validation
void setAge(int a) {
if (a >= 0) ____ = a;
}
void setAge(int a) {
if (a >= 0) age = a;
}
Explanation: If the age is not negative, it is assigned to the age field.
3 Match the setter parts
| Term | Meaning |
|---|---|
void |
Return type |
setAge |
Method name |
int a |
Parameter |
if (a >= 0) |
Validation |