Junior — Middle
Can you explain the principle of encapsulation in object-oriented programming?
sobes.tech AI
Answer from AI
Encapsulation is one of the fundamental principles of object-oriented programming, which involves hiding the internal implementation of an object and providing access to data and methods only through a defined interface.
This allows:
- Protecting internal data from incorrect use or modification from outside.
- Changing the internal implementation without affecting external code that uses the object.
- Simplifying interaction with the object by providing only necessary methods.
In C++, encapsulation is achieved using access specifiers: private, protected, and public. For example:
class BankAccount {
private:
double balance; // hidden field
public:
BankAccount(double initial) : balance(initial) {}
void Deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
double GetBalance() const {
return balance;
}
};
Here, the balance field is hidden from direct access, and interaction with it occurs through the Deposit and GetBalance methods. This prevents incorrect modification of the balance and ensures control over the object's state.