Interview Q&A · Java · 5 questions in this topic
Encapsulation in Practice and Reference Variables — Java Interview Q&A
How Java enforces encapsulation with access control, and what reference variables actually hold. Part of Objects, References & Memory · 294 questions in the Java bank.
How is encapsulation done in Java?
Answer
Encapsulation is done by declaring fields private and exposing them only through public methods such as getters and setters. The setter is the natural place to validate input so the object can never enter an invalid state. Immutable types and records are an even stronger form because there is no setter at all after construction.
Example
public class User { private int age; public int getAge() { return age; } public void setAge(int age) { if (age < 0) { throw new IllegalArgumentException("age must be non-negative"); } this.age = age; } }
💡 Mention records as the modern shortcut for immutable data carriers.
What are reference variables?
Answer
A reference variable holds a reference to an object, or null when it points to nothing. One variable can point to many different objects over time as it is reassigned, while a final reference is locked to the first object it receives. A reference can be typed as a class or as an interface, in which case it can hold any object whose class implements that interface.
Key points
- 1A reference has exactly one declared type but can be repointed to other objects.
- 2A final reference cannot be repointed, though the object itself may still be mutable.
- 3An interface-typed reference can hold any implementing class instance.
Example
Employee emp = new Employee(); // emp is the reference, new Employee() is the object Runnable task = new Thread(); // interface-typed reference to an implementing object
Is encapsulation just writing getters and setters?
Answer
No. Getters and setters are a mechanism; encapsulation is the guarantee that an object’s state cannot reach an invalid value. A class with a public setter for every field, each assigning blindly, exposes exactly the state a public field would. Real encapsulation keeps fields private, exposes only the operations that make sense, validates in one place, and returns copies rather than internal mutable objects so callers cannot bypass the rules.
Key points
- 1The goal is invariant protection, not accessor generation.
- 2A blind setter is as exposed as a public field.
- 3Expose behaviour such as deposit(amount), not storage.
- 4Return defensively copied collections and arrays.
How do you write an immutable class in Java?
Answer
Declare the class final so it cannot be subclassed, make every field private final, set them all in the constructor, and never expose a setter. Copy mutable inputs on the way in and mutable state on the way out, because a final reference to a mutable List still lets callers change the contents. Do not leak this during construction, and if the class holds a mutable helper, keep it entirely private. Records give the same shape with less code when the components are already immutable.
Key points
- 1final class blocks subclassing, which would add mutability.
- 2private final fields with no setters.
- 3Defensive copies for mutable components.
- 4Records are immutable carriers when their components are immutable.
Example
public final class Money { private final int cents; public Money(int cents) { this.cents = cents; } public int cents() { return cents; } }
What actually breaks when a field is public?
Answer
Three things. Any caller can write an invalid value, so every method has to defend against impossible state. The field becomes part of the binary API, so renaming it or changing its type breaks compiled clients. And you lose the ability to change representation later — switching from an int to a value object, adding caching or logging, or making the field computed all become breaking changes. Private fields plus methods keep all three doors open.
Key points
- 1Invalid state can be written from anywhere.
- 2The field name and type become a binary compatibility contract.
- 3Representation changes become breaking changes.
- 4Accessors let validation and computation happen in one place.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission