What is OOP?
Think of OOP like organizing things in your life. OOP is how you organize your code (using objects).
An object is a self-contained unit with:
- State — data it holds (properties/fields)
- Behavior — things it can do (methods)
- Identity — it's a distinct instance, separate from other objects
Example:
A Car object
- Has: color, brand, speed
- Can do: start(), stop(), accelerate()
- And a Vehicle Ownership Document as car identity
So, instead of having a messy program with all logic mixed, OOP groups related data and behavior inside objects — making it organized, reusable, and easy to understand.
Classes & Objects — The Foundation
Before diving into the pillars, you need to understand classes and objects deeply.
A class is a blueprint. An object is a live instance created from that blueprint.
class Car {
// Properties (state)
make: string;
model: string;
year: number;
private mileage: number = 0;
// Constructor — called when creating an instance
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
// Methods (behavior)
drive(miles: number): void {
if (miles > 0) this.mileage += miles;
console.log(`Drove ${miles} miles in the ${this.make} ${this.model}.`);
}
}
// Creating instances (objects) from the class
const car1 = new Car("Toyota", "Camry", 2022);
const car2 = new Car("Honda", "Civic", 2023);
car1 and car2 are completely independent objects — each has its own state.
4 Pillars of OOP (the mindset behind it)
-
Encapsulation
Encapsulation is the process of bundling data (properties) and methods (functions) that operate on that data into a single unit of access (a class). Protect internal data and ensure that objects control how their own data is modified.- Example: When you drive a car, you don’t need to know how the engine works — just press
start.
- Example: When you drive a car, you don’t need to know how the engine works — just press
-
Abstraction
Abstraction means showing only relevant details of an object while hiding its internal implementation. Focus on what an object does, not how it does it.interfaceandabstractare tools to achieve abstraction.- Example: Your car’s “transmission” hides all the complicated process engine.
-
Inheritance
Inheritance allows one class (child/subclass) to inherit properties and methods from another class (parent/superclass), enabling the child class to reuse the code. Use it for genuine "is-a" relationships.- Example: “SportsCar” can inherit from “Car” but adds more speed.
-
Polymorphism
Polymorphism (“many forms”) allows different classes to respond to the same method name in their own unique way. You can call the same method name, but each object does it differently.- Example: playSound() could mean barking for a Dog, or meowing for a Cat.
Top comments (0)