OOP.Encapsulation

🛡️ What is Encapsulation?

Encapsulation is one of the core principles of Object-Oriented Programming (OOP). It means hiding the internal details (data) of an object and only exposing the necessary functionality (methods) to the outside world. This helps to protect the internal state of the object and control how data is accessed or modified.


🔒 Key Idea

“Data should only be accessible through well-defined methods.”


💡 Example

Without Encapsulation (Bad Practice)

class BankAccount {
    double balance;  // Directly accessible - risky!
}

In this example, anyone can directly modify the balance, even putting it into an invalid state like -1000. Not safe!


With Encapsulation (Good Practice)

class BankAccount {
    private double balance;  // Hidden from outside

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }

    public double getBalance() {
        return balance;  // Controlled access
    }
}
This entry was posted in Без рубрики. Bookmark the permalink.