Sobes.tech
Intern

What are the main principles of encapsulation in object-oriented programming?

sobes.tech AI

Answer from AI

Encapsulation is a mechanism that combines data (state) and methods (behavior) into a single unit, and also hides the internal state of an object from the outside world.

Main principles:

  1. Data Hiding: The internal data of an object is accessible only through its methods. Direct access from outside is prohibited.
  2. Controlled access: Access to data is provided through public getters and setters, allowing control over their modification and validation of input values.
  3. Isolation of changes: Changes in the internal implementation of a class do not affect the code that uses this class, provided the signatures of public methods are maintained.

Example in Java:

class Account {
    private double balance; // Data hiding

    public Account(double initialBalance) {
        if (initialBalance >= 0) {
            this.balance = initialBalance;
        } else {
            this.balance = 0;
        }
    }

    public double getBalance() { // Controlled access (getter)
        return balance;
    }

    public void deposit(double amount) { // Controlled access (setter-like method)
        if (amount > 0) {
            this.balance += amount;
        }
    }

    // Isolation of changes: internal logic of deposit can be changed without changing the signature
}

Advantages:

  • Increased data security.
  • Simplified support and modification of code.
  • Reduced dependency between parts of the system.
  • Organized code structure.