What is Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that organizes software around objects rather than functions and logic. An object combines data (attributes) and behaviors (methods) into a single entity, reflecting the way we think about the real world.
💡 Fundamental Concepts
- Class: Blueprint (model) for creating objects
- Object: Instance of a class with specific data
- Attributes: Data/properties of the object
- Methods: Functions/behaviors of the object
From Procedural to OOP
In procedural programming, data and functions are separate. In OOP, they are encapsulated together, making the code more modular and intuitive.
Procedural Approach:
// Separate data
let userName = "Mario";
let userAge = 30;
// Separate functions
function printUser(name, age) {{ '{' }}
console.log(name, age);
{{ '}' }}
OOP Approach:
// Data and behaviors together
class User {{ '{' }}
name: string;
age: number;
print() {{ '{' }}
console.log(this.name, this.age);
{{ '}' }}
{{ '}' }}
The Four Pillars of OOP
1. Encapsulation
Hides internal details, exposing only what is necessary through access modifiers (private, protected, public).
class BankAccount {{ '{' }}
private balance: number = 0;
deposit(amount: number) {{ '{' }}
if (amount > 0) this.balance += amount;
{{ '}' }}
getBalance() {{ '{' }}
return this.balance;
{{ '}' }}
{{ '}' }}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
// account.balance = 999; // ❌ Error: balance is private
2. Inheritance
Allows creating new classes based on existing classes, reusing and extending functionality.
class Animal {{ '{' }}
protected name: string;
constructor(name: string) {{ '{' }}
this.name = name;
{{ '}' }}
move() {{ '{' }}
console.log(`${{ '{' }}this.name{{ '}' }} moves`);
{{ '}' }}
{{ '}' }}
class Dog extends Animal {{ '{' }}
bark() {{ '{' }}
console.log(`${{ '{' }}this.name{{ '}' }} barks`);
{{ '}' }}
{{ '}' }}
const dog = new Dog("Rex");
dog.move(); // "Rex moves"
dog.bark(); // "Rex barks"
3. Polymorphism
Allows treating objects of different classes through a common interface, with specific behaviors for each type.
interface Shape {{ '{' }}
area(): number;
{{ '}' }}
class Circle implements Shape {{ '{' }}
constructor(private radius: number) {{ '{' }}{{ '}' }}
area() {{ '{' }} return Math.PI * this.radius ** 2; {{ '}' }}
{{ '}' }}
class Square implements Shape {{ '{' }}
constructor(private side: number) {{ '{' }}{{ '}' }}
area() {{ '{' }} return this.side ** 2; {{ '}' }}
{{ '}' }}
// Same method, different behaviors
function printArea(shape: Shape) {{ '{' }}
console.log(shape.area());
{{ '}' }}
printArea(new Circle(5)); // ~78.5
printArea(new Square(5)); // 25
4. Abstraction
Hides complexity by showing only essential characteristics. We define "what" an object does, not "how" it does it.
When to Use OOP
✅ Use OOP when:
- The problem domain models well with entities and relationships
- Code reuse through inheritance is needed
- The project is complex and will grow over time
- Working in a team and clear organization is needed
❌ Avoid OOP when:
- The problem is simple (small scripts, utilities)
- Critical performance is needed (class overhead)
- Functional programming is more suitable (data transformations)
Complete Practical Example
class Product {{ '{' }}
constructor(
public name: string,
private price: number
) {{ '{' }}{{ '}' }}
getPrice(): number {{ '{' }}
return this.price;
{{ '}' }}
{{ '}' }}
class ShoppingCart {{ '{' }}
private items: Product[] = [];
addItem(product: Product) {{ '{' }}
this.items.push(product);
{{ '}' }}
getTotal(): number {{ '{' }}
return this.items.reduce((sum, item) => sum + item.getPrice(), 0);
{{ '}' }}
checkout() {{ '{' }}
console.log(`Total: €${{ '{' }}this.getTotal(){{ '}' }}`);
this.items = [];
{{ '}' }}
{{ '}' }}
// Usage
const cart = new ShoppingCart();
cart.addItem(new Product("Laptop", 999));
cart.addItem(new Product("Mouse", 25));
cart.checkout(); // "Total: €1024"
Conclusion
OOP is a powerful paradigm that makes code more organized, reusable, and maintainable. The four pillars (Encapsulation, Inheritance, Polymorphism, Abstraction) work together to create robust and scalable software. In the next articles, we'll explore each pillar in detail with advanced practical examples.
Related deep dive: 02 - Incapsulamento in OOP: Proteggere e Nascondere i Dati.
Related deep dive: 03 - Ereditarietà e Composizione: Riutilizzo del Codice in OOP.
🎯 Key Points
- OOP organizes code around objects with data and behaviors
- Class = blueprint, Object = instance with specific data
- 4 pillars: Encapsulation, Inheritance, Polymorphism, Abstraction
- Use OOP for complex projects that grow over time
Frequently asked questions
What is the main difference between procedural programming and Object-Oriented Programming?
In procedural programming, data and functions are separate, whereas in OOP, they are encapsulated together.
What is the purpose of access modifiers (private, protected, public) in Object-Oriented Programming?
Access modifiers hide internal details, exposing only what is necessary through them.
How does inheritance work in Object-Oriented Programming?
Inheritance allows creating new classes based on existing classes, reusing and extending functionality.
What is the main benefit of abstraction in Object-Oriented Programming?
Abstraction hides complexity by showing only essential characteristics.
Commenti
Caricamento commenti...
Sign in to comment