The 4 Pillars of OOP
OOP helps map real world objects into programs. Real world objects need to:
- Protect internal data
- Hide unnecessary complexity
- Form relationships
- Perform the same action differently
These four needs map directly to the 4 pillars of OOP, one pillar for each need. Each pillar has its own dedicated short note with full code examples, this note is the overview that ties them together.
1. Encapsulation
Wrapping data and related methods inside a class, and controlling access to that data.
Example: BankAccountA BankAccount class keeps its balance private and only lets other code change it through set methods.
- Protected data:
balance(private, not directly accessible) - Access through methods:
deposit(),withdraw()(public)
This solves the "protect internal data" need, no other class can touch balance directly.
2. Abstraction
Hiding unnecessary internal complexity, showing only what the user needs.
Example: TV RemotePressing a button on a TV remote triggers a chain of internal steps the user never sees.
Press Button
Signal Processed
Channel Changes
The user doesn't need to know the internal circuitry, just press and it works. This solves the "hide unnecessary complexity" need.
3. Inheritance
A child class can reuse attributes and methods from a parent class.
Example: Staff SystemFullTimeStaff and PartTimeStaff both reuse the fields and methods already defined on StaffMember.
- Parent: StaffMember
- Children: FullTimeStaff, PartTimeStaff
Child classes inherit the parent's features instead of rewriting them. This solves the "form relationships" need, StaffMember, FullTimeStaff, and PartTimeStaff are connected instead of built as unrelated classes.
4. Polymorphism
The same method can behave differently depending on the object.
Example: Animal SoundsCalling the same makeSound() method on different animal objects produces different results.
makeSound()
Dog โ Bark, Cat โ Meow, Cow โ Moo
Same method call, different behaviour per object. This solves the "perform the same action differently" need.
Key Idea: Encapsulation protects data, Abstraction hides complexity, Inheritance reuses code, Polymorphism changes behaviour per object.
Exam Focus Points
- The 4 pillars are Encapsulation, Abstraction, Inheritance, and Polymorphism.
- Each pillar solves a specific real world modeling need, protecting data, hiding complexity, reusing code through relationships, and varying behaviour.
- Encapsulation and Abstraction both hide something (data vs complexity); Inheritance reuses code through a class relationship, Polymorphism varies behaviour per object or per method signature.
Summary
- OOP is built on 4 pillars: Encapsulation, Abstraction, Inheritance, Polymorphism.
- Encapsulation protects data through private fields and public methods.
- Abstraction hides internal complexity behind simple actions.
- Inheritance lets a child class reuse a parent class's features.
- Polymorphism lets the same method produce different behaviour per object.