Programming Paradigms
Object-Oriented Programming (OOP)
Core OOP concepts — classes, objects, and the four pillars: encapsulation, abstraction, inheritance, and polymorphism — with Python examples.
- OOP
- Programming Paradigms
- Python
What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm built around objects — bundles of data (attributes) and behavior (methods) — rather than functions and logic alone. A class is the blueprint; an object is an instance created from that blueprint.
The Four Pillars
1. Encapsulation
Bundling data and the methods that operate on it inside a single unit (a class), and restricting direct access to some of an object’s internal state.
2. Abstraction
Exposing only the essential features of an object while hiding the implementation details — the user of a class doesn’t need to know how a method works, just what it does.
3. Inheritance
A class (child/subclass) can reuse and extend the attributes and methods of another class (parent/superclass), avoiding duplicated code.
4. Polymorphism
The same interface (method name) behaves differently depending on the object calling it — as seen above, speak() produces different output for Dog and Cat without the caller needing to know which subclass it’s dealing with.
OOP vs Procedural Programming
| aspect | procedural | object-oriented |
|---|---|---|
| Organization | Functions operating on data | Objects bundling data + behavior |
| Reusability | Copy-paste or shared functions | Inheritance & composition |
| Data safety | Data usually global/shared | Encapsulation restricts access |
| Scaling | Harder as codebase grows | Easier to model complex domains |
| Examples | C, shell scripts | Python, Java, C++, C# |
Composition over Inheritance
A common modern guideline: prefer composition (an object has-a another object) over deep inheritance chains (an object is-a type of another), since composition keeps classes more flexible and easier to test.
Key Takeaways
- Class = blueprint, Object = instance of that blueprint.
- Encapsulation protects internal state; Abstraction hides complexity.
- Inheritance promotes reuse; Polymorphism lets different objects respond to the same call in their own way.
- Favor composition over inheritance when relationships aren’t a strict “is-a” hierarchy.