TypeScript Object-Oriented Programming (OOP)

Introduction

In this chapter, we will explore Object-Oriented Programming (OOP) in TypeScript. OOP is a programming paradigm based on the concept of objects, which can contain data and code. Understanding OOP is essential for writing modular, reusable, and maintainable TypeScript programs.

Table of Contents

  • Definition
  • Classes and Objects
  • Constructors
  • Access Modifiers
  • Properties and Methods
  • Inheritance
  • Method Overriding
  • Abstract Classes and Methods
  • Interfaces
  • Complete Example with Output
  • Conclusion

Definition

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects. These objects can contain properties (data) and methods (functions) that operate on the data. OOP is used to structure a software program into simple, reusable pieces of code blueprints (usually called classes), which are then used to create individual instances of objects.

Classes and Objects

Definition

A class is a blueprint for creating objects. An object is an instance of a class. Classes encapsulate data and behavior in a single unit.

Example

This example demonstrates how to define a class and create an object.

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet(): string {
    return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
  }
}

let person = new Person("Ramesh", 25);
console.log(person.greet()); // Output: Hello, my name is Ramesh and I am 25 years old.

Output

Hello, my name is Ramesh and I am 25 years old.

Constructors

Definition

A constructor is a special method in a class that is called when an object of the class is instantiated. It is used to initialize the object's properties.

Example

This example demonstrates a class with a constructor to initialize its properties.

class Car {
  model: string;
  year: number;

  constructor(model: string, year: number) {
    this.model = model;
    this.year = year;
  }

  display(): string {
    return `This car is a ${this.model} from ${this.year}.`;
  }
}

let car = new Car("Toyota", 2020);
console.log(car.display()); // Output: This car is a Toyota from 2020.

Output

This car is a Toyota from 2020.

Access Modifiers

Definition

Access modifiers in TypeScript define the visibility of class properties and methods. The three main access modifiers are public, private, and protected.

Example

This example demonstrates the use of access modifiers in a class.

class Employee {
  public name: string;
  private salary: number;
  protected department: string;

  constructor(name: string, salary: number, department: string) {
    this.name = name;
    this.salary = salary;
    this.department = department;
  }

  getDetails(): string {
    return `Name: ${this.name}, Department: ${this.department}`;
  }
}

let employee = new Employee("Suresh", 50000, "HR");
console.log(employee.getDetails()); // Output: Name: Suresh, Department: HR

Output

Name: Suresh, Department: HR

Properties and Methods

Definition

Properties are variables that belong to a class. Methods are functions that belong to a class and define its behavior.

Example

This example demonstrates a class with properties and methods.

class Book {
  title: string;
  author: string;

  constructor(title: string, author: string) {
    this.title = title;
    this.author = author;
  }

  getSummary(): string {
    return `${this.title} is written by ${this.author}.`;
  }
}

let book = new Book("TypeScript Basics", "John Doe");
console.log(book.getSummary()); // Output: TypeScript Basics is written by John Doe.

Output

TypeScript Basics is written by John Doe.

Inheritance

Definition

Inheritance is a mechanism where a new class (subclass) inherits the properties and methods of an existing class (superclass).

Example

This example demonstrates class inheritance.

class Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  makeSound(): string {
    return `${this.name} makes a sound.`;
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }

  makeSound(): string {
    return `${this.name} barks.`;
  }
}

let dog = new Dog("Tommy");
console.log(dog.makeSound()); // Output: Tommy barks.

Output

Tommy barks.

Method Overriding

Definition

Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass.

Example

This example demonstrates method overriding in a subclass.

class Bird {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  fly(): string {
    return `${this.name} is flying.`;
  }
}

class Penguin extends Bird {
  constructor(name: string) {
    super(name);
  }

  fly(): string {
    return `${this.name} cannot fly.`;
  }
}

let penguin = new Penguin("Pingu");
console.log(penguin.fly()); // Output: Pingu cannot fly.

Output

Pingu cannot fly.

Abstract Classes and Methods

Definition

An abstract class is a class that cannot be instantiated and is meant to be subclassed. An abstract method is a method that must be implemented by subclasses.

Example

This example demonstrates an abstract class with an abstract method.

abstract class Shape {
  abstract getArea(): number;

  display(): string {
    return `The area is ${this.getArea()}.`;
  }
}

class Circle extends Shape {
  radius: number;

  constructor(radius: number) {
    super();
    this.radius = radius;
  }

  getArea(): number {
    return Math.PI * this.radius * this.radius;
  }
}

let circle = new Circle(5);
console.log(circle.display()); // Output: The area is 78.53981633974483.

Output

The area is 78.53981633974483.

Interfaces

Definition

An interface in TypeScript is a syntactical contract that an entity should conform to. It defines the shape of an object, including its properties and methods, without providing implementation.

Example

This example demonstrates an interface and its implementation in a class.

interface Vehicle {
  model: string;
  year: number;

  getDetails(): string;
}

class Bike implements Vehicle {
  model: string;
  year: number;

  constructor(model: string, year: number) {
    this.model = model;
    this.year = year;
  }

  getDetails(): string {
    return `This bike is a ${this.model} from ${this.year}.`;
  }
}

let bike = new Bike("Yamaha", 2019);
console.log(bike.getDetails()); // Output: This bike is a Yamaha from 2019.

Output

This bike is a Yamaha from 2019.

Complete Example with Output

In this section, we will combine the examples into a single TypeScript file, compile it to JavaScript, and run it to see the output.

TypeScript Code

You can test the following code in the TypeScript Playground:

// Classes and Objects
class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet(): string {
    return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
  }
}

let person = new Person("Ramesh", 25);
console.log(person.greet()); // Output: Hello, my name is Ramesh and I am 25 years old.

// Constructors
class Car {
  model: string;
  year: number;

  constructor(model: string, year: number) {
    this.model = model;
    this.year = year;
  }

  display(): string {
    return `This car is a ${this.model} from ${this.year}.`;
  }
}

let car = new Car("Toyota", 2020);
console.log(car.display()); // Output: This car is a Toyota from 2020.

// Access Modifiers
class Employee {
  public name: string;
  private salary: number;
  protected department: string;

  constructor(name: string, salary: number, department: string) {
    this.name = name;
    this.salary = salary;
    this.department = department;
  }

  getDetails(): string {
    return `Name: ${this.name}, Department: ${this.department}`;
  }
}

let employee = new Employee("Suresh", 50000, "HR");
console.log(employee.getDetails()); // Output: Name: Suresh, Department: HR

// Properties and Methods
class Book {
  title: string;
  author: string;

  constructor(title:

 string, author: string) {
    this.title = title;
    this.author = author;
  }

  getSummary(): string {
    return `${this.title} is written by ${this.author}.`;
  }
}

let book = new Book("TypeScript Basics", "John Doe");
console.log(book.getSummary()); // Output: TypeScript Basics is written by John Doe.

// Inheritance
class Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  makeSound(): string {
    return `${this.name} makes a sound.`;
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }

  makeSound(): string {
    return `${this.name} barks.`;
  }
}

let dog = new Dog("Tommy");
console.log(dog.makeSound()); // Output: Tommy barks.

// Method Overriding
class Bird {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  fly(): string {
    return `${this.name} is flying.`;
  }
}

class Penguin extends Bird {
  constructor(name: string) {
    super(name);
  }

  fly(): string {
    return `${this.name} cannot fly.`;
  }
}

let penguin = new Penguin("Pingu");
console.log(penguin.fly()); // Output: Pingu cannot fly.

// Abstract Classes and Methods
abstract class Shape {
  abstract getArea(): number;

  display(): string {
    return `The area is ${this.getArea()}.`;
  }
}

class Circle extends Shape {
  radius: number;

  constructor(radius: number) {
    super();
    this.radius = radius;
  }

  getArea(): number {
    return Math.PI * this.radius * this.radius;
  }
}

let circle = new Circle(5);
console.log(circle.display()); // Output: The area is 78.53981633974483.

// Interfaces
interface Vehicle {
  model: string;
  year: number;

  getDetails(): string;
}

class Bike implements Vehicle {
  model: string;
  year: number;

  constructor(model: string, year: number) {
    this.model = model;
    this.year = year;
  }

  getDetails(): string {
    return `This bike is a ${this.model} from ${this.year}.`;
  }
}

let bike = new Bike("Yamaha", 2019);
console.log(bike.getDetails()); // Output: This bike is a Yamaha from 2019.

Conclusion

In this chapter, we covered Object-Oriented Programming (OOP) in TypeScript, including classes and objects, constructors, access modifiers, properties and methods, inheritance, method overriding, abstract classes and methods, and interfaces. We provided a complete example with its output to illustrate how OOP concepts work in TypeScript. Understanding OOP is essential for writing modular, reusable, and maintainable TypeScript programs.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare