STUDYECRAT Java : OOP - Encapsulation
60s
Java OOP - Encapsulation
Prove your skills in this interactive quiz
Live Code
Run snippets directly
Timed
60s per question
Scored
Earn 3D badges
★ Java Encapsulation: Key Interview Points
1. Private Fields - The Foundation
class Employee {
private String name; // Field is private
public String getName() { return name; }
} // Direct 'name' access is now restricted
private String name; // Field is private
public String getName() { return name; }
} // Direct 'name' access is now restricted
- Tip: Always start with private fields - upgrade visibility only if absolutely necessary
- Real Use: Prevents external code from corrupting object state (e.g., setting negative salary values)
2. Getter/Setter Validation
public void setAge(int age) {
if (age < 0 || age > 120) {
throw new IllegalArgumentException("Invalid age");
}
this.age = age;
} // Business logic enforced in setter
if (age < 0 || age > 120) {
throw new IllegalArgumentException("Invalid age");
}
this.age = age;
} // Business logic enforced in setter
- Tip: Setters are where you validate/transform inputs before storage
- Real Use: E-commerce systems use this to validate product prices (non-negative)
3. Immutable Design Pattern
public final class BankAccount {
private final String accountNumber;
public BankAccount(String num) { this.accountNumber = num; }
public String getAccountNumber() { return accountNumber; }
} // No setters + final fields = Immutability
private final String accountNumber;
public BankAccount(String num) { this.accountNumber = num; }
public String getAccountNumber() { return accountNumber; }
} // No setters + final fields = Immutability
- Tip: Critical for thread-safety - no synchronization needed
- Real Use: Used in currency classes (java.util.Currency) and security tokens
4. Defensive Copying for Collections
private List transactions;
// Getter implementation
public List getTransactions() {
return new ArrayList<>(transactions); // Return copy
} // Prevents external list modification
// Getter implementation
public List
return new ArrayList<>(transactions); // Return copy
} // Prevents external list modification
- Tip: Also use Collections.unmodifiableList() for read-only exposure
- Real Use: Banking apps use this to protect transaction histories
5. Secure Data Handling
private char[] password;
public void clearPassword() {
Arrays.fill(password, '\0'); // Overwrite in memory
} // Safer than String which stays in memory pool
public void clearPassword() {
Arrays.fill(password, '\0'); // Overwrite in memory
} // Safer than String which stays in memory pool
- Tip: Always use char[] for passwords - Strings are immutable and linger in memory
- Real Use: Required for PCI-DSS compliance in payment systems
💡 Pro Interview Tip
When asked about encapsulation, always mention data protection, controlled access, and validation together. Give examples of how you've used it to prevent bugs - interviewers love real-world context!