What is Object-Oriented Programming (OOP)?
General • Concepts Explained • 7 min read
OOP organizes code around objects. Learn the four pillars: encapsulation, abstraction, inheritance, and polymorphism.
What is Object-Oriented Programming (OOP)?
OOP is a programming paradigm that organizes code around objects instead of functions. Most modern languages — Java, Python, C#, JavaScript — support OOP. Understanding OOP is essential for writing clean, reusable code.
What is OOP?
OOP structures programs as collections of objects. Each object contains data (properties) and behavior (methods). Think of a car: it has properties like color and speed, and methods like accelerate and brake.
The Four Pillars of OOP
1. Encapsulation
Bundling data and methods together, hiding internal details:
class BankAccount {
#balance = 0; // Private property
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
2. Abstraction
Hiding complex implementation, showing only what's needed:
// User doesn't need to know how email is sent
function sendEmail(to, subject, body) {
// Complex SMTP logic hidden here
console.log(`Email sent to ${to}`);
}
3. Inheritance
Creating new classes from existing ones:
class Animal {
speak() { return "Some sound"; }
}
class Dog extends Animal {
speak() { return "Woof!"; }
}
class Cat extends Animal {
speak() { return "Meow!"; }
}
4. Polymorphism
Same method name, different behavior:
const animals = [new Dog(), new Cat()];
animals.forEach(animal => console.log(animal.speak()));
// "Woof!"
// "Meow!"
Classes in JavaScript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}
const john = new Person("John", 25);
console.log(john.greet()); // "Hi, I'm John"
OOP vs Functional Programming
| Feature | OOP | Functional |
|---|---|---|
| Structure | Objects and classes | Functions |
| Data | Inside objects | Passed between functions |
| Best for | Complex systems | Data transformations |
Note: Most real-world applications use both OOP and functional programming. Learn OOP fundamentals, then combine approaches as needed.