Java Encapsulation
Encapsulation means wrapping an object's data safely inside the class and controlling access to it through methods. It is one of the core ideas of object-oriented programming, and it keeps your data from being changed in careless or invalid ways.
The idea behind encapsulation
The recipe for encapsulation is simple: mark your fields as private so outside code cannot touch them directly, then provide public methods that read and update those fields. These methods are traditionally called getters and setters. Because every change now flows through a method, you get a single place to add validation.
- Declare the fields private.
- Add a public getter method to return each field's value.
- Add a public setter method to change each field's value.
- Put any validation rules inside the setter.
A class with getters and setters
public class Person {
private String name; // hidden from outside code
// Getter: lets others read the name
public String getName() {
return name;
}
// Setter: lets others change the name
public void setName(String newName) {
this.name = newName;
}
}Because outside code can no longer reach the field directly, the setter becomes the perfect spot to reject bad values. In the example below, the class refuses to store a negative age.
Protecting data with validation
public class Player {
private int score;
public int getScore() {
return score;
}
public void setScore(int score) {
if (score >= 0) { // only accept valid values
this.score = score;
} else {
System.out.println("Score cannot be negative.");
}
}
public static void main(String[] args) {
Player p = new Player();
p.setScore(50);
p.setScore(-10); // rejected
System.out.println(p.getScore()); // Outputs 50
}
}Exercise: Java Encapsulation
What is the core idea of encapsulation in Java?