What is Getter and Setter in Java: Simple Explanation and Example
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.
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 } }
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.