Skip to content
C

Java Interview Questions

Encapsulation Interview Questions

Data hiding, access modifiers, and designing classes that protect their own state.

Question 1: What is encapsulation in Java?

Ans

Encapsulation means keeping an object's internal state, its fields, hidden from the outside and only allowing controlled access through public methods. It lets a class enforce its own rules about how its data can be read or changed, instead of letting other code modify it directly and possibly leave it in an invalid state.

Example

java
class Account { private double balance; public void deposit(double amount) { if (amount > 0) balance += amount; } public double getBalance() { return balance; } }

Important Point

Private fields plus public getters/setters are a common implementation, but true encapsulation is about protecting invariants, not just about hiding fields mechanically.

Question 2: What are Java's access modifiers, and how do they support encapsulation?

Ans

Java has four access levels: private (only the same class), package-private/default (same package), protected (same package plus subclasses), and public (everywhere). Encapsulation typically uses the narrowest level that still works — private fields, and public methods only for what genuinely needs to be exposed.

Example

java
private int balance; // hidden protected void logChange() { } // visible to subclasses public double getBalance() { return balance; } // exposed deliberately

Important Point

Top-level classes can only be public or package-private — private and protected aren't valid there.

Continue Your Preparation