Information is stored within the object. It is hidden from the outside world.
- A phone stores several phone numbers
- We can’t read the numbers directly from the SIM card
- Rather phone-set reads this information for us
Data and behavior are tightly coupled inside an object. Both the information structure and implementation details of its operations are hidden from the outer world.
A Phone stores phone numbers in digital format and knows how to convert it into human-readable characters
We don’t know
- How the data is stored
- How it is converted to human-readable characters
Advantages of Encapsulation
- Low complexity
- Easy understanding
Object has an interface
- An object encapsulates data and behavior
- So how objects interact with each other?
- Each object provides an interface (operations)
- Other objects communicate through this interface
Example – Interface of a Car
- Steer Wheels
- Change Gear
- Apply Brakes
- Turn Lights On/Off
Provides services offered by the object interface.
- Data structures to hold object state
- Functionality that provides required services
- Physical structure of gear box
- Mechanism to change gear