Encapsulation is one of the core principles of object-oriented programming (OOP). It involves bundling the data (attributes) and the methods (functions) that operate on the data into a single unit, typically called a class.
The key aspects of encapsulation include:
Consider a simple class representing a bank account:
class BankAccount {
private var balance: Double = 0.0 // Private data member
// Public method to deposit money
public func deposit(amount: Double) {
if amount > 0 {
balance += amount
}
}
// Public method to withdraw money
public func withdraw(amount: Double) -> Bool {
if amount > 0 && amount <= balance {
balance -= amount
return true
} else {
return false
}
}
// Public method to get the current balance
public func getBalance() -> Double {
return balance
}
}