Junior
What is encapsulation in object-oriented programming (OOP)?
sobes.tech AI
Answer from AI
Encapsulation is a mechanism that combines data and methods (functions) that work with this data into a single object. The implementation details of the object are hidden from the outside world, providing access to the data only through a specific interface (public methods).
Main goals:
- Data hiding: Prevents direct access to the internal states of the object, protecting them from incorrect modification.
- Access control: Allows defining which parts of the object are accessible from outside.
- Manageability: Simplifies changing the internal implementation without affecting the code that uses this object.
- Security: Ensures data integrity.
Example in Java:
class BankAccount {
private double balance; // Data is hidden
public BankAccount(double initialBalance) {
if (initialBalance >= 0) {
this.balance = initialBalance;
} else {
this.balance = 0;
}
}
public double getBalance() { // Public method for access
return balance;
}
public void deposit(double amount) { // Public method for modification
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) { // Public method for modification
if (amount > 0 && balance >= amount) {
balance -= amount;
}
}
}
// Usage example
// BankAccount account = new BankAccount(1000);
// double currentBalance = account.getBalance(); // Access via method
// account.deposit(500); // Modification via method
// account.balance = -100; // Cannot directly change balance