# Object-Oriented Programming OOP in TypeScrip

### 1\. **Classes**

**Definition:** A class is a blueprint for creating objects. It defines properties and methods that the created objects will have.

**Key Features:**

* Encapsulates data and methods into a single unit.
    
* Supports inheritance, allowing one class to extend another.
    
* Can have constructors to initialize objects.
    

**How it’s Implemented in TypeScript:** TypeScript uses the `class` keyword to define classes. You can also define methods and properties within the class.

**Example Code:**

```typescript
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.`);
    }
}

const person = new Person('Alice', 30);
person.greet(); 
```

### 2\. **Encapsulation**

* **Definition**: Encapsulation means keeping some details of a class hidden so only certain parts are accessible. This is done using access modifiers like `public`, `private`, and `protected`.
    
    * `public`: Accessible from anywhere.
        
    * `private`: Only accessible inside the class.
        
    * `protected`: Accessible in the class and subclasses.
        
* ```typescript
          class 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(1000);
          account.deposit(500);
          console.log(account.getBalance());  
    ```
    

Here, `balance` is private, so it can’t be accessed or modified directly from outside.

### 3\. **Inheritance**

* **Definition**: Inheritance allows one class (child class) to inherit properties and methods from another class (parent class). This helps to reuse code.
    
* ```typescript
          class Animal {
              sound() {
                  console.log("Animal sound");
              }
          }
          
          class Dog extends Animal {
              sound() {
                  console.log("Bark");
              }
          }
          
          const myDog = new Dog();
          myDog.sound(); 
    ```
    

Here, `Dog` class inherits from the `Animal` class and overrides the `sound` method.

### 4\. **Polymorphism**

* **Definition**: Polymorphism means one thing (a method) can have many forms. For example, a method can behave differently in different classes.
    
    * **Method Overriding**: Changing a method's behavior in a child class.
        
    * **Method Overloading**: Simulating multiple methods with different arguments (achieved through optional parameters in TypeScript).
        
* ```typescript
          class Shape {
              area(): number {
                  return 0;
              }
          }
          
          class Circle extends Shape {
              radius: number;
          
              constructor(radius: number) {
                  super();
                  this.radius = radius;
              }
          
              area(): number {
                  return Math.PI * this.radius * this.radius;
              }
          }
          
          const circle = new Circle(10);
          console.log(circle.area());  
    ```
    
    ### 5\. **Abstraction**
    
    * **Definition**: Abstraction means hiding complex details and showing only the important parts. In TypeScript, this is done using abstract classes or interfaces.
        
    * ```typescript
              class Employee {
                  abstract getSalary(): number;
              
                  showDetails() {
                      console.log("Employee details");
                  }
              }
              
              class FullTimeEmployee extends Employee {
                  getSalary(): number {
                      return 5000;
                  }
              }
              
              const emp = new FullTimeEmployee();
              emp.showDetails();  
              console.log(emp.getSalary());  
        ```
        
    
    In the example above, `Employee` is abstract and can't be directly created, but it serves as a template for `FullTimeEmployee`.
    
    **Additional Concepts:**
    
    #### **Interfaces**
    
    * **Definition**: An interface defines the structure of an object without implementing any behavior. Classes that use the interface must follow its structure.
        
    * ```typescript
           interface User {
                  name: string;
                  age: number;
                  greet(): void;
              }
              
              class Customer implements User {
                  name: string;
                  age: number;
              
                  constructor(name: string, age: number) {
                      this.name = name;
                      this.age = age;
                  }
              
                  greet() {
                      console.log(`Hello, I am ${this.name}`);
                  }
              }
              
              const customer = new Customer("Alice", 25);
              customer.greet();  
        ```
        
    
    #### **Constructor Overloading**
    
    * **Definition**: TypeScript doesn’t support multiple constructors directly, but you can achieve this by using optional parameters in one constructor.
        
    * ```typescript
              class Product {
                  name: string;
                  price: number;
              
                  constructor(name: string, price?: number) {
                      this.name = name;
                      this.price = price ?? 0;  // Default price if not provided
                  }
              }
              
              const laptop = new Product("Laptop", 1000);
              const mouse = new Product("Mouse");
              
              console.log(laptop);  
              console.log(mouse);  
        ```
        
    
    #### **Getters and Setters**
    
    * **Definition**: Getters and setters allow controlled access to class properties. A getter retrieves the value, while a setter changes it.
        
    * ```typescript
              class UserAccount {
                  private _username: string;
              
                  get username(): string {
                      return this._username;
                  }
              
                  set username(value: string) {
                      if (value.length < 4) {
                          throw new Error("Username must be at least 4 characters long.");
                      }
                      this._username = value;
                  }
              }
              
              const user = new UserAccount();
              user.username = "JohnDoe"; 
              console.log(user.username);  
        ```
        
    
    TypeScript implements OOP concepts just like traditional OOP languages (like Java), but with some unique TypeScript features like strong typing, interfaces, and optional parameters. These concepts help in organizing code, improving reusability, and making applications more maintainable.
