what is encapsulation in java
Encapsulation in Java is the practice of bundling data and the methods that work on that data into one class, while hiding the internal state from direct outside access. In simple terms, you keep fields private and expose controlled access through public methods like getters and setters.
Quick Scoop
Encapsulation helps you:
- Protect data from unwanted changes.
- Control how values are read or updated.
- Make code easier to maintain and debug.
How it works
A common Java pattern looks like this:
- Declare fields as
private. - Provide
publicgetter methods to read values. - Provide
publicsetter methods to update values, often with validation.
For example, a Student class might hide name and only allow changes
through setName() so you can reject empty values.
Why it matters
Encapsulation is useful because it:
- Prevents accidental misuse of class data.
- Supports data hiding.
- Makes future changes safer, since other classes depend on the public methods instead of the raw fields.
Tiny example
java
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here, name cannot be changed directly from outside the class; it must go
through the setter.
TL;DR
Encapsulation in Java means hide the data, expose only what is needed, and control access through methods.