Encapsulation and information hiding are important principles in object-oriented programming (OOP) that promote modular, maintainable, and secure code. Let’s explore each concept:
Example demonstrating encapsulation and information hiding:
class BankAccount {
private $balance; // Private attribute
// Constructor
public function __construct($initialBalance) {
$this->balance = $initialBalance;
}
// Method to deposit money
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}
// Method to withdraw money
public function withdraw($amount) {
if ($amount > 0 && $amount <= $this->balance) {
$this->balance -= $amount;
}
}
// Method to get the current balance
public function getBalance() {
return $this->balance;
}
}
// Creating an instance of the BankAccount class
$account = new BankAccount(1000);
// Accessing the public method to deposit money
$account->deposit(500);
// Accessing the public method to withdraw money
$account->withdraw(200);
// Accessing the public method to get the balance
echo "Current balance: $" . $account->getBalance();
Explanation:
BankAccount
class encapsulates the data (balance) and methods (deposit, withdraw, getBalance) related to managing a bank account.$balance
attribute is marked as private, hiding it from direct access outside the class. This ensures that the balance can only be modified through the deposit and withdraw methods, maintaining data integrity.deposit
, withdraw
, and getBalance
provide controlled access to the internal state of the object, allowing clients to interact with the bank account without directly accessing its private attributes.By encapsulating data and hiding implementation details, encapsulation and information hiding enhance the security, maintainability, and flexibility of object-oriented code.
Leave A Comment