Encapsulation is the bundling of an object's data and the methods that operate on that data within a class. Information hiding restricts direct access to the object's internal state, requiring other code to interact through a controlled public interface.
How They Work
In object-oriented programming (OOP), a class defines both attributes, which store an object's state, and methods, which define its behaviour. Encapsulation places these related components together in one class.
Information hiding is then achieved using access modifiers. Attributes are commonly declared private, while selected methods are declared public. This prevents external code from changing data directly in ways that could make the object invalid.
class BankAccount
private balance
public constructor(startingBalance)
if startingBalance >= 0
balance = startingBalance
public deposit(amount)
if amount > 0
balance = balance + amount
public getBalance()
return balance
Here, balance is encapsulated with the methods of BankAccount and hidden from direct external access. A different class cannot assign a negative value directly to balance; it must use deposit, which validates the amount. This helps preserve the object's data integrity.
| Concept | Meaning | Example |
|---|---|---|
| Encapsulation | Combines attributes and methods within one class | BankAccount contains balance, deposit, and getBalance |
| Information hiding | Conceals implementation details and restricts direct access | balance is private |
| Public interface | Provides controlled ways to interact with an object | deposit() and getBalance() are public |
A common misconception is that encapsulation and information hiding are identical. They are closely related, but encapsulation concerns organizing data and behaviour into a class, whereas information hiding concerns controlling what external code can access.
IB Exam Technique
For a B3.1 Fundamentals of OOP response, define both terms separately and use a single-class example. Explain that private attributes protect state while public methods provide controlled access; do not merely state that encapsulation means “making everything private.”