Lesson 19: Implementing Getters and Setters
Since we hide data using the private access modifier (Encapsulation), we need designated public methods to safely read and write that data. These are known as Accessor methods (getters) and Mutator methods (setters).
1. Getters (Accessors)
- Purpose: To retrieve (read) the value of a private variable.
- Naming Convention: Typically starts with
get(orisfor boolean fields). - Return Type: Matches the variable type.
2. Setters (Mutators)
- Purpose: To modify (write) the value of a private variable.
- Naming Convention: Typically starts with
set. - Return Type: Always
void. - Crucially, setters are where you enforce validation and business rules.
Example: The Student Class
java public class Student { private String name; private int age;
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
// Validation can happen here:
if (name != null && name.length() > 1) {
this.name = name;
}
}
// Getter for age
public int getAge() {
return age;
}
// Setter for age (with validation)
public void setAge(int age) {
if (age > 0 && age < 120) {
this.age = age;
}
}
}
Usage
java Student s = new Student(); s.setAge(25); // Valid, sets the age s.setAge(-5); // Invalid input, age remains at default/uninitialized value System.out.println(s.getAge()); // Reads the validated age