Activity 10: Object-Oriented Programming OOP in TypeScript

Let's delve into how Object-Oriented Programming (OOP) concepts are implemented in TypeScript. Each concept is broken down with definitions, key features, TypeScript implementation, and example code.
1. Class and Object
Definition:
Class: A blueprint for creating objects. It defines properties and methods that the objects created from the class will have.
Object: An instance of a class, created using the
newkeyword. It contains the properties and methods defined by the class.
Key Features:
Class: Defines the structure and behavior of objects.
Object: Holds the data and methods defined by the class.
How it’s Implemented in TypeScript:
Define a class using the
classkeyword.Create an object by instantiating the class with the
newkeyword.
Example Code:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): void {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// Creating an object of the Person class
const person = new Person('Alice', 30);
person.greet();
2. Encapsulation
Definition:
- Encapsulation is the practice of hiding the internal details of an object and exposing only the necessary parts. This helps in protecting the internal state of an object from unintended interference.
Key Features:
Public: Members are accessible from anywhere.
Private: Members are accessible only within the class.
Protected: Members are accessible within the class and by subclasses.
How it’s Implemented in TypeScript:
- Use access modifiers (
public,private,protected) to control access to class members.
Example Code:
class BankAccount {
private balance: number = 0;
deposit(amount: number): void {
if (amount > 0) {
this.balance += amount;
}
}
withdraw(amount: number): void {
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
}
}
getBalance(): number {
return this.balance;
}
}
const account = new BankAccount();
account.deposit(100);
account.withdraw(50);
console.log(account.getBalance()); // 50
3. Inheritance
Definition:
- Inheritance allows one class (subclass or derived class) to inherit properties and methods from another class (base class or parent class).
Key Features:
Extends Keyword: Used to create a subclass.
Method Overriding: Subclasses can override methods of the parent class.
How it’s Implemented in TypeScript:
Use the
extendskeyword to inherit from a base class.Override methods by defining them in the subclass with the same name as in the parent class.
Example Code:
class Animal {
makeSound(): void {
console.log('Some generic animal sound');
}
}
class Dog extends Animal {
makeSound(): void {
console.log('Woof! Woof!');
}
}
const dog = new Dog();
dog.makeSound(); // Woof! Woof!
4. Polymorphism
Definition:
- Polymorphism allows objects of different classes to be treated as objects of a common superclass. It includes method overriding (runtime polymorphism) and method overloading (compile-time polymorphism).
Key Features:
Method Overriding: Subclass methods replace superclass methods at runtime.
Method Overloading: Multiple methods with the same name but different parameters.
How it’s Implemented in TypeScript:
Method Overriding: Define a method in a subclass with the same name as in the parent class.
Method Overloading: Define multiple method signatures with the same name but different parameter lists.
Example Code:
Method Overriding:
class Shape {
area(): number {
return 0;
}
}
class Rectangle extends Shape {
constructor(private width: number, private height: number) {
super();
}
area(): number {
return this.width * this.height;
}
}
const rectangle = new Rectangle(10, 5);
console.log(rectangle.area()); // 50
Method Overloading:
class Printer {
print(message: string): void;
print(message: string, times: number): void;
print(message: string, times?: number): void {
if (times) {
for (let i = 0; i < times; i++) {
console.log(message);
}
} else {
console.log(message);
}
}
}
const printer = new Printer();
printer.print('Hello'); // Hello
printer.print('Hello', 3); // Hello Hello Hello
5. Abstraction
Definition:
- Abstraction is the concept of hiding the complex implementation details and showing only the necessary features of an object.
Key Features:
Abstract Classes: Cannot be instantiated directly and are used to define abstract methods that must be implemented by subclasses.
Interfaces: Define a contract that classes must follow but do not provide implementation.
How it’s Implemented in TypeScript:
Use
abstractkeyword to define abstract classes and methods.Use
interfaceto define contracts.
Example Code:
Abstract Classes:
abstract class Shape {
abstract area(): number;
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
const circle = new Circle(10);
console.log(circle.area()); // 314.159...
Interfaces:
interface Drawable {
draw(): void;
}
class Circle implements Drawable {
constructor(private radius: number) {}
draw(): void {
console.log(`Drawing a circle with radius ${this.radius}`);
}
}
const circle = new Circle(10);
circle.draw(); // Drawing a circle with radius 10
Additional OOP Concepts
Interfaces:
Definition:
- An interface defines a structure for objects, specifying what properties and methods they must have without providing the implementation.
Key Features:
- Defines a contract for classes.
How it’s Implemented in TypeScript:
- Use
interfacekeyword to define the structure.
Example Code:
interface Person {
name: string;
age: number;
greet(): void;
}
class Employee implements Person {
constructor(public name: string, public age: number) {}
greet(): void {
console.log(`Hello, I am ${this.name}`);
}
}
const employee = new Employee('Bob', 40);
employee.greet(); // Hello, I am Bob
Constructor Overloading:
Definition:
- Constructor overloading allows a class to have multiple constructors with different parameters.
Key Features:
- Provides flexibility in object instantiation.
How it’s Implemented in TypeScript:
- Use multiple constructor signatures.
Example Code:
class Rectangle {
constructor(public width: number, public height: number);
constructor(side: number);
constructor(widthOrSide: number, height?: number) {
if (height === undefined) {
this.width = this.height = widthOrSide;
} else {
this.width = widthOrSide;
this.height = height;
}
}
area(): number {
return this.width * this.height;
}
}
const square = new Rectangle(10);
const rectangle = new Rectangle(10, 20);
console.log(square.area()); // 100
console.log(rectangle.area()); // 200
Getters and Setters:
Definition:
- Getters and setters provide controlled access to the properties of a class.
Key Features:
Getter: Retrieves the value of a property.
Setter: Updates the value of a property.
How it’s Implemented in TypeScript:
- Use
getandsetkeywords to define getters and setters.
Example Code:
class Person {
private _age: number;
constructor(age: number) {
this._age = age;
}
get age(): number {
return this._age;
}
set age(value: number) {
if (value >= 0) {
this._age = value;
} else {
console.log('Age must be positive');
}
}
}
const person = new Person(25);
console.log(person.age); // 25
person.age = 30;
console.log(person.age); // 30
person.age = -5; // Age must be positive
This comprehensive guide should help you understand how TypeScript implements core OOP concepts and how you can leverage its features to write robust, maintainable code.
Reference Link:
Object Oriented Programming with TypeScript

