☕ Java Beginner

What is encapsulation in Java?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Java basics — a prerequisite for any developer role.

Answer

Encapsulation is the OOP principle of bundling data (fields) and the methods that operate on that data within a single class, while restricting direct access to the fields from outside the class. This is implemented by declaring fields as private and providing public getter and setter methods to control access. Encapsulation protects the internal state of an object from unauthorized or invalid changes — a setter can validate the new value before setting it. It also hides the implementation details, so the internal representation can change without affecting other classes that use the object.

Pro Tip

This topic has Java-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.