allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œWith God all things are possible.โ€
[Matthew 19:26]


Getters, Setters


10.2.1 Why Use Getters and Setters?

Because fields are private for safety, you still need a controlled way to read and write their values from outside.

This is where getters and setters come in:

  • A getter lets you read a fieldโ€™s value.

  • A setter lets you change a fieldโ€™s value โ€” but only with your validation rules.

Together, they act like gatekeepers.
They give you full control over:

  • What is visible,

  • What is changeable,

  • And how.


10.2.2 Example of Getters and Setters

Letโ€™s see a simple Person class that uses getters and setters.

java
public class Person { private String name; private int age; public String getName() { return name; // getter } public void setName(String name) { this.name = name; // setter } public int getAge() { return age; // getter } public void setAge(int age) { if (age > 0) { // validation this.age = age; } } }

Key points:

  • Fields are private.

  • getName() and getAge() return the current values.

  • setName() and setAge() update values โ€” setAge() checks for valid input.

This pattern keeps the classโ€™s internal data safe and prevents illegal values.


10.2.3 Mini Lab: Putting It Together

Below is a mini program that shows how to use getters and setters in practice.

java
public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if (age > 0) { this.age = age; } } public static void main(String[] args) { Person p = new Person(); p.setName("Alice"); p.setAge(25); System.out.println("Name: " + p.getName()); System.out.println("Age: " + p.getAge()); } }

When you run it:

  • The Person object p has private fields.

  • You set them safely through setters.

  • You read them safely through getters.

  • Direct modification is impossible from outside.