Encapsulation in Java
Encapsulation means bundling an object's data together with the methods that operate on it, and restricting direct outside access to that data — in practice, this means private fields paired with public methods that control exactly how those fields can be read or changed. It's less about hiding data out of secrecy and more about controlling access: a setter method can validate a new value before accepting it, reject an invalid one outright, or update a second, related field automatically, none of which would be possible if outside code could just write directly into the field itself.
Encapsulation also protects a class's freedom to change its own internal implementation later. As long as the public methods keep behaving the same way from the outside, the private fields and logic behind them can be restructured freely, without breaking any code elsewhere that depends on the class.
Private fields
Data that shouldn't be reached into directly from outside the class is marked private.
Public methods as the controlled entry point
Getters and setters, or more specific, purpose-built methods, are how outside code is allowed to interact with that data.
Validation in a setter
A setter can check a new value and reject it, rather than blindly accepting whatever's assigned.
Read-only exposure
Providing only a getter, with no matching setter, exposes a field for reading without ever allowing outside code to change it.
Freedom to change implementation later
As long as public method behavior stays the same, private internals can be restructured without breaking dependent code.
public class Temperature { private double celsius; public void setCelsius(double value) { if (value >= -273.15) { celsius = value; } } public double getCelsius() { return celsius; } public static void main(String[] args) { Temperature t = new Temperature(); t.setCelsius(-500); System.out.println("After invalid set: " + t.getCelsius()); t.setCelsius(25); System.out.println("After valid set: " + t.getCelsius()); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.