Sobes.tech
Junior

What else does encapsulation include besides data hiding?

sobes.tech AI

Answer from AI

Besides data hiding (concealing the internal implementation of an object from the outside world), encapsulation includes:

  • Combining data and methods that operate on that data into a single object. This creates self-sufficient programming units.
  • Access control to data. Using access modifiers (public, protected, private) determines how other objects can interact with the internal state of the object. This helps ensure data integrity and prevent incorrect modifications.
  • Reducing cohesion. A high level of encapsulation contributes to changes within one object minimally affecting other parts of the system.

Example:

<?php

class BankAccount {
    private $balance; // Data hiding

    public function __construct($initialBalance) {
        if ($initialBalance >= 0) {
            $this->balance = $initialBalance;
        } else {
            $this->balance = 0;
        }
    }

    public function deposit($amount) {
        if ($amount > 0) {
            $this->balance += $amount; // Methods work with data
        }
    }

    public function withdraw($amount) {
        if ($amount > 0 && $amount <= $this->balance) {
            $this->balance -= $amount; // Access control and integrity
            return true;
        }
        return false;
    }

    public function getBalance() {
        return $this->balance; // Providing controlled access
    }
}

?>

In this example, data hiding (private $balance) is combined with providing public methods (deposit, withdraw, getBalance) that control access and modifications to this data. This unites data and logic into a single object and ensures encapsulation.