Junior
What are the advantages of applying the principle of encapsulation in real systems?
sobes.tech AI
Answer from AI
Encapsulation enhances security and reliability of code by hiding the internal implementation of objects and providing controlled access to their state through methods.
Advantages:
- Access control: Hides internal details, allowing changes without affecting external code. Achieved through access modifiers (
private,protected,public).public class Account { private double balance; // Hiding internal state public double getBalance() { // Controlled access return balance; } public void deposit(double amount) { if (amount > 0) { balance += amount; } } } - Flexibility and maintainability: Changes in internal implementation do not affect external usage, as access is through public interface. Simplifies refactoring and scaling.
- Reliability: Controls object state changes and prevents invalid values. Setters can include validation logic.
public class PositiveNumber { private int value; public int getValue() { return value; } public void setValue(int value) { if (value >= 0) { // Validation this.value = value; } else { // Error handling or exception System.err.println("Value must be non-negative."); } } } - Ease of use: Users do not need to know how data is stored or processed internally. They interact only through public methods.
- Reduced coupling: Decreases dependency between system parts, making testing and reuse easier.