0
0
JavaConceptBeginner · 3 min read

What is Getter and Setter in Java: Simple Explanation and Example

In Java, getter and setter are special methods used to read and update the value of private variables in a class. They help control access to data by allowing safe retrieval and modification without exposing the variables directly.
⚙️

How It Works

Imagine you have a box with a lock. You don't want everyone to open the box directly, but you want to let some people see what's inside or change what's inside safely. In Java, private variables are like that locked box. You can't access them directly from outside the class.

Getters and setters are like the keys to that box. A getter lets you look inside the box (read the value), and a setter lets you change what's inside (update the value). This way, you control how the data is accessed or changed, which helps keep your program safe and organized.

💻

Example

This example shows a simple Java class with a private variable and its getter and setter methods.

java
public class Person {
    private String name; // private variable

    // Getter method to read the name
    public String getName() {
        return name;
    }

    // Setter method to update the name
    public void setName(String newName) {
        this.name = newName;
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Alice"); // set the name
        System.out.println("Name: " + person.getName()); // get and print the name
    }
}
Output
Name: Alice
🎯

When to Use

Use getters and setters whenever you want to protect your class's data from being changed directly. This is important in real-world programs where data must be controlled carefully, like in banking apps or games.

They also let you add extra checks when changing data. For example, a setter can make sure a number is positive before saving it. This helps avoid mistakes and keeps your program working correctly.

Key Points

  • Getters read private variables safely.
  • Setters update private variables with control.
  • They help keep data safe and organized.
  • Setters can include checks to prevent errors.
  • Using them follows good programming practice called encapsulation.

Key Takeaways

Getters and setters control access to private variables in Java classes.
They help protect data by preventing direct access from outside the class.
Setters can include validation to keep data correct and safe.
Using getters and setters is a key part of good object-oriented programming.
They make your code easier to maintain and less error-prone.