Encapsulation is an Object-Oriented Programming (OOP) principle that combines data and the methods that operate on that data into a single unit, known as a class. It also restricts direct access to an object's internal state and allows controlled access through methods such as getters and setters.
Key Points: • Encapsulation helps protect data from unauthorized access and modification. • Class fields are typically declared as private to hide internal implementation details. • Public getter and setter methods provide controlled access to the data. • It improves security, maintainability, and code flexibility. • Encapsulation is one of the core pillars of Object-Oriented Programming.
Example: Consider a BankAccount class. The account balance should not be modified directly from outside the class. Instead, users should access or update it through dedicated methods that can perform validation.
Code Example:
class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
public class Demo {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
System.out.println(account.getBalance());
}
}Output:
1000.0
Benefits of Encapsulation:
• Protects object data from direct access • Enables validation before updating data • Reduces coupling between components • Makes code easier to maintain and modify • Improves application security and reliability
Real-World Example:
An ATM machine does not allow users to directly access or modify the bank's database. Instead, users interact through controlled operations such as withdraw, deposit, and balance inquiry. This is a practical example of encapsulation.
Interview Tip: A concise interview answer is:
"Encapsulation is the process of bundling data and related methods into a single class while restricting direct access to the data. It is typically achieved using private fields and public getter/setter methods, improving security, maintainability, and data integrity."