On Day 20, we learn about getters and setters, which are methods used to read and update private fields of a class. This concept is part of encapsulation, one of the four pillars of Object-Oriented Programming (OOP).
1. Why Use Getters and Setters?
Instead of making fields public, we keep them private and provide controlled access through methods. This ensures data safety and flexibility.
2. Example: Getter and Setter
class Student {
private String name;
// setter
public void setName(String n) {
name = n;
}
// getter
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setName("Alice"); // using setter
System.out.println("Student name: " + s.getName()); // using getter
}
}
Explanation: The field name is private. The setName() method assigns a value, and getName() returns it. This protects direct access to the field.
3. Adding Validation in Setters
Setters can include validation logic to prevent invalid data.
class Student {
private int age;
public void setAge(int a) {
if (a > 0) {
age = a;
} else {
System.out.println("Invalid age!");
}
}
public int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setAge(-5); // invalid
s.setAge(20); // valid
System.out.println("Student age: " + s.getAge());
}
}
Explanation: Without validation, a student could have a negative age. With encapsulation, rules are enforced inside the setter.
4. Read-only and Write-only Fields
Sometimes we want only reading or only writing access:
class Student {
private String id;
// read-only
public String getId() {
return id;
}
// write-only
private String password;
public void setPassword(String p) {
password = p;
}
}
Explanation: id can only be read (no setter), while password can only be set (no getter).
Summary
- Encapsulation hides fields and provides controlled access.
- Getter methods return field values.
- Setter methods assign values (with optional validation).
- Improves security, flexibility, and maintainability of code.