Activity 10: Object-Oriented Programming OOP in TypeScript

1. Class and Object
Definition:
A class is a blueprint or template for creating objects. It defines the properties (attributes) and methods (functions) that objects of that type will have.
An object is an instance of a class. It represents a real-world entity and can hold specific data and perform actions.
Key Features:
Encapsulation: Bundling data (properties) and behavior (methods) together.
Abstraction: Hiding implementation details and exposing only relevant information.
Implementation in TypeScript:
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'm ${this.age} years old.`; } } const person1 = new Person("Alice Gou", 30); console.log(person1.greet()); // Output: "Hello, my name is Alice Gou and I'm 30 years old."
2. Encapsulation
Definition:
Encapsulation restricts direct access to an object’s internal state (properties).
It ensures that data is accessed and modified through well-defined methods (getters and setters).
Key Features:
- Access Modifiers: TypeScript provides
public,private, andprotectedkeywords to control visibility.
- Access Modifiers: TypeScript provides
Example:
class BankAccount { private balance: number = 0; deposit(amount: number): void { this.balance += amount; } getBalance(): number { return this.balance; } } const account = new BankAccount(); account.deposit(100); console.log(account.getBalance()); // Output: 100
3. Inheritance
Definition:
Inheritance allows a class (subclass or derived class) to inherit properties and methods from another class (base class or superclass).
It promotes code reuse and hierarchy.
Key Features:
extendsKeyword: Used to create a subclass.Method Overriding: Subclasses can override methods from the parent class.
Example:
class Animal { makeSound(): string { return "Generic animal sound"; } } class Dog extends Animal { makeSound(): string { return "Woof!"; } } const myDog = new Dog(); console.log(myDog.makeSound()); // Output: "Woof!"
4. Polymorphism
Definition:
Polymorphism allows objects of different classes to be treated uniformly.
Two types: Compile-time (method overloading) and Runtime (method overriding).
Example:
class Shape { area(): number { return 0; } } class Circle extends Shape { constructor(private radius: number) { super(); } area(): number { return Math.PI * this.radius * this.radius; } } const myCircle: Shape = new Circle(5); console.log(myCircle.area()); // Output: 78.54 (runtime polymorphism)
5. Abstraction
Definition:
Abstraction hides complex implementation details and exposes only essential features.
Achieved using abstract classes and interfaces.
Example:
abstract class Vehicle { abstract startEngine(): void; } class Car extends Vehicle { startEngine(): void { console.log("Car engine started."); } } const myCar = new Car(); myCar.startEngine(); // Output: "Car engine started."