Encapsulation enhances software security and data integrity by restricting direct access to an object's internal data. Instead of exposing data publicly, it allows controlled access through methods that can validate, filter, or protect information before it is modified.
Key Points: • Encapsulation hides sensitive data by making fields private. • Access to data is controlled through getter and setter methods. • Validation logic can be applied before updating object state. • It prevents unauthorized or accidental modification of data. • Encapsulation helps maintain data consistency and application reliability.
Example: Consider an Employee class where salary should never be set to a negative value. By keeping the salary field private and updating it through a setter method, invalid data can be prevented.
Code Example:
class Employee {
private double salary;
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
if (salary > 0) {
this.salary = salary;
} else {
System.out.println("Invalid Salary");
}
}
}
public class Demo {
public static void main(String[] args) {
Employee employee = new Employee();
employee.setSalary(-5000);
System.out.println(employee.getSalary());
}
}Output:
Invalid Salary 0.0
Without Encapsulation:
If the salary field were public, any part of the application could assign invalid values directly:
employee.salary = -5000;
This could lead to inconsistent and unreliable data.
How Encapsulation Improves Security:
• Hides critical data from external classes • Prevents unauthorized modifications • Allows validation before updates • Protects business rules and constraints • Reduces the risk of accidental data corruption
How Encapsulation Maintains Integrity:
• Ensures objects remain in a valid state • Prevents invalid data entry • Centralizes validation logic • Preserves consistency throughout the application
Real-World Example:
A banking system does not allow users to directly modify their account balance in the database. All transactions must go through controlled operations such as deposit() and withdraw(), where validation and security checks are performed. This ensures both security and data integrity.
Interview Tip: A concise interview answer is:
"Encapsulation improves security by hiding internal data and allowing access only through controlled methods. It enhances data integrity by validating inputs and preventing unauthorized or invalid modifications, ensuring that objects always remain in a consistent and valid state."