What are Getters and Setters?
In OOP, it is considered good practice to keep an object’s data private.
Instead of allowing other classes to access or modify the data directly, we use getters and setters.
Key intution:
- A getter returns the value of an attribute.
- A setter changes the value of an attribute.
Using setters and getters helps protect an object’s data and gives the class control over how its attributes are accessed and modified.
Can you identify what OOP property is this? :)
Rationale
Section titled “Rationale”Consider the following Student class:
class Student { public String name; public int age;}Since both attributes are public, anyone can modify them directly.
Student student = new Student();
student.name = "Alice";student.age = -10;Can you identify the problem?
There is nothing prevents someone from assigning an invalid age!
Instead, we can make the attributes private and provide methods to access them safely.
(OOP principles ftw!)
How to create getters and setters?
Section titled “How to create getters and setters?”class Student {
private String name; private int age;
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public void setAge(int age) { if (age >= 0) { this.age = age; } }
public int getAge() { return age; }}
public class Main { public static void main(String[] args) {
Student student = new Student();
student.setName("Alice"); student.setAge(20);
System.out.println(student.getName()); // Outputs "Alice" System.out.println(student.getAge()); // Outputs 20 }}In this example:
setName()changes the student’s name.getName()returns the student’s name.setAge()only accepts non-negative values.getAge()returns the student’s age.
Notice that the class now controls how its data is modified.
Instead of accessing the attributes directly, the program uses the setter methods to assign values and the getter methods!
Summary
Section titled “Summary”- Getters return the value of an attribute.
- Setters modify the value of an attribute.
- Attributes are usually declared
private. - Getters and setters are usually declared
public. - Using getters and setters protects an object’s data and allows the class to validate values before storing them.
This is one of the most common ways that encapsulation is done in Java.