Encapsulation (OOP) (OCR A-Level Computer Science): Revision Notes
📚 Revision Notes
Encapsulation (OOP)
Overview
Encapsulation is a core principle of Object-Oriented Programming (OOP) that restricts direct access to an object's data and methods, ensuring that its internal state is only modified in a controlled manner. Encapsulation allows for the creation of a well-defined interface while hiding the internal workings of a class, which enhances data security, modularity, and code maintainability.
Key Concepts of Encapsulation
Private and Public Access
- Private Attributes and Methods: In encapsulation, certain attributes and methods are made private (accessible only within the class). Private attributes often have a leading underscore (
_) or double underscore (__) in their names to signal restricted access. - Public Methods (Getters and Setters): Public methods allow controlled access to private attributes by exposing a set of actions the object can perform. Through getters and setters, external code can read or modify these attributes without accessing them directly.
Purpose of Encapsulation
- Data Security: By restricting direct access to internal data, encapsulation prevents accidental or unauthorised modifications, protecting data integrity.
- Control Over Modifications: Encapsulation allows the developer to control how and when data is changed, often with validation checks in setter methods to ensure that data stays consistent and valid.
- Modularity and Maintainability: Encapsulation keeps code organised by grouping related data and methods within the class, making it easier to trace, update, and debug.
Getters and Setters (Accessors and Mutators)
- Getter Methods (Accessors): These methods retrieve the value of private attributes. They provide read-only access to the data, allowing external code to access data without exposing the attribute itself.
- Setter Methods (Mutators): These methods allow controlled modification of private attributes. They can include validation logic to prevent invalid data from being assigned.
Example: Encapsulating Bank Account Data
infoNote
Here's an example of encapsulation in a BankAccount class where balance is kept private and accessed or modified only through getter and setter methods.
class BankAccount:
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder # Public attribute
self.__balance = balance # Private attribute
# Getter method to retrieve balance
def get_balance(self):
return self.__balance
# Setter method to update balance with validation
def set_balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Error: Balance cannot be negative.")
# Method to deposit funds, with private balance access
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"${amount} deposited. New balance: ${self.__balance}")
else:
print("Error: Deposit amount must be positive.")
Explanation of the Example
- Private Attribute:
__balanceis private, meaning it can't be accessed or modified directly from outside the class. - Public Methods:
get_balance()provides controlled access to__balance.set_balance()allows updates to__balanceonly if the new amount is non-negative, preventing invalid assignments.deposit()updates__balanceusing internal logic, allowing positive deposits while protecting__balancefrom external modification.
Benefits of Encapsulation
- Data Protection: Private attributes prevent unauthorised access and modification, helping secure sensitive information.
- Control Over Data Integrity: By using setters, encapsulation ensures data validation, reducing errors and maintaining consistent object state.
- Modularity: Encapsulation groups related data and methods within a single class, keeping code organised and easier to manage.
- Ease of Maintenance: Encapsulated code is easier to update or debug, as changes are isolated within the class without affecting external code.
Note Summary
infoNote
Common Mistakes with Encapsulation
- Directly Modifying Private Attributes: Attempting to access or modify private attributes directly from outside the class will lead to an error.
- Lack of Validation in Setters: Failing to implement validation in setter methods can lead to invalid data, compromising data integrity.
- Improper Use of
self: Forgetting to useselfwhen accessing attributes within a class can result in errors and confusion.
infoNote
Key Takeaways
- Encapsulation restricts access to an object's internal data and operations, allowing controlled access through public methods.
- Private attributes and methods keep data secure and prevent unintended modification.
- Getters and Setters (accessor and mutator methods) enable controlled read and write access, with setters providing an opportunity for data validation.
- Encapsulation promotes data integrity, modularity, and code maintainability, essential for building reliable and secure OOP-based applications.