ACTIVITY 10: Object-Oriented Programming OOP in TypeScript | Aligan, Rhed N.

ACTIVITY 10: Object-Oriented Programming OOP in TypeScript | Aligan, Rhed N.

1. Class and Object

  1. Class

    • A class is a blueprint for creating objects, encapsulating data (attributes) and behavior (methods).

    • How Classes Act as Blueprints: Classes define the structure and behavior that objects will have, allowing for the creation of multiple instances with similar properties but different values.

    • Example of Defining a Class in TypeScript:

        typescriptCopy codeclass Animal {
            name: string;
            sound: string;
      
            constructor(name: string, sound: string) {
                this.name = name;
                this.sound = sound;
            }
      
            makeSound() {
                console.log(`${this.name} says ${this.sound}`);
            }
        }
      
        const dog = new Animal("Dog", "Woof");
        dog.makeSound(); // Dog says Woof
      

Object

  • An object is an instance of a class that contains state (properties) and behavior (methods).

  • Example of Creating an Object:

      typescriptCopy codeconst cat = new Animal("Cat", "Meow");
      cat.makeSound(); // Cat says Meow
    

2. Encapsulation

  • Encapsulation is the practice of bundling the data (properties) and methods (functions) that operate on the data into a single unit (class) and restricting access to some of the object's components.

  • It helps hide the internal details of a class, protecting the integrity of the data and preventing unauthorized access.

  • Access Modifiers:

    • public: Properties and methods are accessible from anywhere.

    • private: Properties and methods are accessible only within the class.

    • protected: Properties and methods are accessible within the class and by subclasses.

  • Example:

      typescriptCopy codeclass BankAccount {
          private balance: number;
    
          constructor(initialBalance: number) {
              this.balance = initialBalance;
          }
    
          public deposit(amount: number) {
              this.balance += amount;
          }
    
          public getBalance(): number {
              return this.balance;
          }
      }
    
      const account = new BankAccount(100);
      account.deposit(50);
      console.log(account.getBalance()); // 150
      // account.balance; // Error: Property 'balance' is private
    

3. Inheritance

  • Inheritance is a mechanism where one class (child or derived class) can inherit properties and methods from another class (parent or base class).

  • How to Use the extends Keyword: The extends keyword is used to create a subclass that inherits from a parent class.

  • Method Overriding: Subclasses can override methods from the parent class to provide specific implementations.

  • Example:

      typescriptCopy codeclass Vehicle {
          start() {
              console.log("Vehicle starting");
          }
      }
    
      class Car extends Vehicle {
          start() {
              console.log("Car starting");
          }
      }
    
      const myCar = new Car();
      myCar.start(); // Car starting
    

4. Polymorphism

  • Polymorphism allows different classes to be treated as instances of the same parent class. It provides a way to perform a single action in different forms.

  • Method Overriding (Runtime Polymorphism): This occurs when a subclass provides a specific implementation of a method that is already defined in its parent class.

  • Method Overloading (Compile-time Polymorphism): This allows multiple methods with the same name but different parameter types or numbers.

  • Example of Method Overriding:

      typescriptCopy codeclass 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 rect = new Rectangle(5, 10);
      console.log(rect.area()); // 50
    
  • Example of Method Overloading:

      typescriptCopy codeclass Display {
          show(value: string): void;
          show(value: number): void;
          show(value: any): void {
              console.log(value);
          }
      }
    
      const display = new Display();
      display.show("Hello"); // Hello
      display.show(123);     // 123
    

5. Abstraction

  • Abstraction is the concept of hiding the complex implementation details and exposing only the necessary features of an object.

  • It simplifies the interaction with complex systems by providing a simplified interface.

  • Using Abstract Classes and Interfaces:

    • Abstract Class: A class that cannot be instantiated and may contain abstract methods that must be implemented in derived classes.

    • Interface: Defines a contract that classes can implement without providing implementation details.

  • Example of Abstract Class:

      typescriptCopy codeabstract class Animal {
          abstract makeSound(): void;
      }
    
      class Dog extends Animal {
          makeSound(): void {
              console.log("Woof");
          }
      }
    
      const dog = new Dog();
      dog.makeSound(); // Woof
    
  • Example of Interface:

      typescriptCopy codeinterface Shape {
          area(): number;
      }
    
      class Circle implements Shape {
          constructor(private radius: number) {}
    
          area(): number {
              return Math.PI * this.radius * this.radius;
          }
      }
    
      const circle = new Circle(5);
      console.log(circle.area()); // 78.53981633974483
    

6. Interfaces

  • An interface in TypeScript defines the structure of an object, specifying what properties and methods an object should have without providing the implementation.

  • Interfaces help achieve abstraction by ensuring that classes adhere to a specific structure.

  • Example:

      typescriptCopy codeinterface Person {
          name: string;
          age: number;
          greet(): void;
      }
    
      class Employee implements Person {
          constructor(public name: string, public age: number) {}
    
          greet(): void {
              console.log(`Hello, my name is ${this.name}`);
          }
      }
    
      const emp = new Employee("Alice", 30);
      emp.greet(); // Hello, my name is Alice
    

7. Constructor Overloading

  • TypeScript allows multiple constructor definitions using optional parameters or union types to handle different initialization scenarios.

  • Example:

      typescriptCopy codeclass User {
          name: string;
          age: number;
    
          constructor(name: string);
          constructor(name: string, age: number);
          constructor(name: string, age?: number) {
              this.name = name;
              this.age = age || 0; // Default age if not provided
          }
      }
    
      const user1 = new User("John");
      const user2 = new User("Jane", 25);
      console.log(user1); // User { name: 'John', age: 0 }
      console.log(user2); // User { name: 'Jane', age: 25 }
    

8. Getters and Setters

  • Getters and setters are methods that allow controlled access to an object's properties. Getters retrieve property values, while setters update them.

  • Example:

      typescriptCopy codeclass Rectangle {
          private _width: number;
          private _height: number;
    
          constructor(width: number, height: number) {
              this._width = width;
              this._height = height;
          }
    
          get area(): number {
              return this._width * this._height;
          }
    
          set width(value: number) {
              if (value > 0) {
                  this._width = value;
              }
          }
    
          set height(value: number) {
              if (value > 0) {
                  this._height = value;
              }
          }
      }
    
      const rect = new Rectangle(10, 20);
      console.log(rect.area); // 200
      rect.width = 15;
      console.log(rect.area); // 300
    

In Summarization in all of this activity 10:

Object-Oriented Programming (OOP) in TypeScript includes essential concepts like classes and objects, where classes serve as blueprints for creating objects. Encapsulation hides internal details using access modifiers, while inheritance allows classes to inherit properties and methods from others. Polymorphism enables treating different classes as instances of the same parent class, supporting method overriding and overloading. Abstraction simplifies complex systems using abstract classes and interfaces, which define structures without implementation. Additionally, TypeScript allows constructor overloading for flexible initialization and provides getters and setters to control property access, promoting better data integrity and maintainability.