Encapsulation
ICT2622 - Object-Oriented Analysis · Object-Oriented Concepts
Encapsulation
Encapsulation is one of the fundamental principles of object-oriented programming (OOP). It refers to the bundling of data and methods that operate on that data within a single unit, known as a class. Encapsulation restricts access to some of the object's components, which is a means of preventing unintended interference and misuse of the methods and data.
What is Encapsulation?
In encapsulation, the internal state of an object is hidden from the outside world. This is achieved through access modifiers. An access modifier is a keyword used to specify the visibility of a class member (attributes and methods). The main access modifiers in C++ are:
- Public: Members declared as public are accessible from outside the class.
- Private: Members declared as private are only accessible within the class itself.
- Protected: Members declared as protected are accessible within the class and by derived classes.
Remember: Use encapsulation to protect the integrity of your data by controlling access to it.
Creating a Class with Encapsulation
Let’s look at an example of encapsulation in C++. We will create a class named BankAccount that encapsulates the properties of a bank account.
class BankAccount {
private:
double balance;
public:
BankAccount(double initialBalance) {
balance = initialBalance;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
double getBalance() {
return balance;
}
};In this example:
- The
balanceattribute is declared as private. This means it cannot be accessed directly from outside the class. - The methods
deposit,withdraw, andgetBalanceare declared as public. These methods provide controlled access to thebalanceattribute.
Using the Encapsulated Class
Now, let’s see how to use the BankAccount class in a program.
int main() {
BankAccount account(1000.0); // Create a new bank account with an initial balance of 1000.0
account.deposit(500.0); // Deposit 500.0
account.withdraw(200.0); // Withdraw 200.0
double currentBalance = account.getBalance(); // Get the current balance
std::cout << "Current Balance: " << currentBalance << std::endl;
return 0;
}In this program:
- A new
BankAccountobject is created with an initial balance of 1000.0 rand. - 500.0 rand is deposited into the account.
- 200.0 rand is withdrawn from the account.
- The current balance is retrieved and printed to the console.
Tip: Always validate the data before making changes to the internal state of an object. This helps maintain the integrity of the data.
Benefits of Encapsulation
Encapsulation provides several benefits:
- Data Hiding: It hides the internal state of an object from the outside world. This reduces the risk of unintended interference.
- Controlled Access: It allows you to control how data is accessed and modified through public methods.
- Improved Maintainability: Changes to the internal implementation of a class do not affect other parts of the program, as long as the public interface remains the same.
- Increased Security: Sensitive data can be protected from outside access.
Common Mistakes with Encapsulation
Watch out: A common mistake is to declare all members of a class as public. This defeats the purpose of encapsulation and can lead to data corruption.
Encapsulation in Inheritance
When using inheritance, encapsulation still applies. A derived class can access protected members of the base class but cannot access private members. This ensures that the base class maintains control over its internal state while allowing some level of access to derived classes.
Here is an example:
class SavingsAccount : public BankAccount {
private:
double interestRate;
public:
SavingsAccount(double initialBalance, double rate) : BankAccount(initialBalance) {
interestRate = rate;
}
void applyInterest() {
double interest = getBalance() * interestRate;
deposit(interest);
}
};In this example:
- The
SavingsAccountclass inherits fromBankAccount. - It has its own private member
interestRate. - The method
applyInterestuses the public methods of the base class to apply interest to the account.
Conclusion
Encapsulation is a key principle of object-oriented programming that helps in managing complexity by hiding the internal state of an object. It allows you to control access to the data and methods of a class, ensuring that the data remains valid and secure.
Summary
- Encapsulation combines data and methods in a class.
- Access modifiers (public, private, protected) control visibility.
- Encapsulation protects the integrity of data.
- Encapsulation improves maintainability and security.
Check your understanding
- What is the purpose of encapsulation in object-oriented programming?
- Explain the difference between public, private, and protected access modifiers.
- How does encapsulation help in maintaining data integrity?
- What happens to private members of a base class when a derived class is created?