All academies

Introduction to OOP

Why object-oriented programming exists and how it models the real world.

14 minLevel 1 of 20

What is Object-Oriented Programming?

Object-Oriented Programming (OOP) structures software around objects — units that combine data (state) with behavior (methods). Instead of loose procedures over shared data, you model the problem as collaborating objects.

TypeScript and NestJS lean on OOP: classes, interfaces, inheritance, and dependency injection power modules, providers, and controllers.

A first object
class User {
  constructor(public name: string, public email: string) {}
  greet() { return `Hello, I'm ${this.name}`; }
}
const alice = new User("Alice", "alice@example.com");
console.log(alice.greet());
console.log("email:", alice.email);

Why OOP exists

As programs grow, unstructured code becomes hard to change. OOP addresses this with four pillars:

  • Encapsulation — hide internals; expose a clear API
  • Abstraction — work with essentials, not every detail
  • Inheritance — reuse and specialize shared behavior
  • Polymorphism — treat different types through one contract

NestJS uses these so you can swap a repository, mock a service in tests, or grow a module without rewriting the app.

Procedural vs OOP
const account = { balance: 100 };
function deposit(acc: { balance: number }, amount: number) {
  acc.balance += amount;
}
deposit(account, 50);
console.log("Procedural:", account.balance);

class BankAccount {
  constructor(private balance: number) {}
  deposit(amount: number) { this.balance += amount; }
  getBalance() { return this.balance; }
}
const acct = new BankAccount(100);
acct.deposit(50);
console.log("OOP:", acct.getBalance());

How this maps to NestJS

In NestJS almost everything is a class:

  • Controllers handle HTTP
  • Services hold business logic
  • Repositories talk to the database
  • Modules wire providers

The IoC container creates these classes and injects dependencies — which only works cleanly if you design with OOP and interfaces.

Nest-shaped wiring
class UsersRepository {
  findAll() { return [{ id: 1, name: "Ada" }]; }
}
class UsersService {
  constructor(private readonly repo: UsersRepository) {}
  list() { return this.repo.findAll(); }
}
class UsersController {
  constructor(private readonly users: UsersService) {}
  getUsers() { return this.users.list(); }
}
const controller = new UsersController(new UsersService(new UsersRepository()));
console.log(controller.getUsers());

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

OOP primarily organizes software around: