Activity 11: Object-Oriented Programming OOP in TypeScript

1. Class and Object in TypeScript
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. It contains the properties and behaviors defined by the class.
Key Features:
Classes can have properties (data) and methods (functions).
Objects are created by instantiating a class using the
newkeyword.
How it’s Implemented in TypeScript:
TypeScript uses the class keyword to define a class and the new keyword to create objects.
Example Code:
typescriptCopy codeclass Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// Create an object
let person1 = new Person("Alice", 25);
person1.greet(); // Output: Hello, my name is Alice and I am 25 years old.
2. Encapsulation in TypeScript
Definition:
Encapsulation is the concept of restricting access to certain components of an object and only exposing the necessary parts. This helps in hiding the internal details of a class and protects its data from outside interference.
Key Features:
Encapsulation is achieved using access modifiers:
public: Accessible from anywhere.private: Accessible only within the class.protected: Accessible within the class and its subclasses.
How it’s Implemented in TypeScript:
TypeScript uses the public, private, and protected keywords to define access levels.
Example Code:
typescriptCopy codeclass Car {
public model: string;
private year: number;
constructor(model: string, year: number) {
this.model = model;
this.year = year;
}
public getYear() {
return this.year;
}
private calculateAge() {
return new Date().getFullYear() - this.year;
}
}
let myCar = new Car("Toyota", 2015);
console.log(myCar.model); // Public, accessible
console.log(myCar.getYear()); // Access through public method
// myCar.year; // Error: year is private
3. Inheritance in TypeScript
Definition:
Inheritance is an OOP concept where one class (child class) inherits the properties and methods of another class (parent class). This allows for code reuse and the creation of hierarchical relationships between classes.
Key Features:
The
extendskeyword is used for class inheritance.Child classes can access and override parent class methods and properties.
How it’s Implemented in TypeScript:
Inheritance is achieved using the extends keyword. The child class can call the parent class’s constructor using super().
Example Code:
typescriptCopy codeclass Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name); // Call the parent class constructor
}
speak() {
console.log(`${this.name} barks.`);
}
}
let dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks.
4. Polymorphism in TypeScript
Definition:
Polymorphism allows objects of different classes to be treated as instances of the same class through a common interface or inheritance. It enables one interface to be used for different underlying forms (either through method overriding or overloading).
Key Features:
Method overriding: A child class can provide a specific implementation of a method already defined in its parent class.
Method overloading: Defining multiple methods with the same name but different signatures.
How it’s Implemented in TypeScript:
TypeScript supports method overriding using inheritance and method overloading using function declarations with different signatures.
Example Code (Method Overriding):
typescriptCopy codeclass 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;
}
}
let shape: Shape = new Circle(5);
console.log(shape.area()); // Polymorphism in action, output: 78.54
5. Abstraction in TypeScript
Definition:
Abstraction is the process of hiding the implementation details and showing only the essential features of an object. It provides a clear interface for interactions with an object while keeping its internal workings hidden.
Key Features:
Achieved through abstract classes and interfaces.
Abstract classes cannot be instantiated directly; they are meant to be extended by subclasses.
Interfaces define the structure without implementation.
How it’s Implemented in TypeScript:
Abstract classes are defined using the abstract keyword. Interfaces define contracts for objects.
Example Code (Abstract Class):
typescriptCopy codeabstract class Employee {
constructor(public name: string) {}
abstract work(): void; // Abstract method
}
class Developer extends Employee {
work() {
console.log(`${this.name} is coding.`);
}
}
let dev = new Developer("Alice");
dev.work(); // Output: Alice is coding.
6. Interfaces in TypeScript
Definition:
An interface defines the structure (or contract) that a class or object must follow without providing any implementation. It ensures that objects have the necessary properties and methods.
Key Features:
Interfaces define what an object should look like.
Classes can implement multiple interfaces.
How it’s Implemented in TypeScript:
The interface keyword is used to define interfaces. Classes that implement interfaces must adhere to the structure defined by the interface.
Example Code:
typescriptCopy codeinterface Animal {
name: string;
sound(): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
sound() {
console.log("Woof!");
}
}
let dog: Animal = new Dog("Buddy");
dog.sound(); // Output: Woof!
7. Constructor Overloading in TypeScript
Definition:
Constructor overloading is a feature where a class can have multiple constructors with different parameters. TypeScript achieves this using optional parameters.
Key Features:
- TypeScript does not support multiple constructors in the traditional sense, but it allows constructor overloading using optional parameters.
How it’s Implemented in TypeScript:
Optional parameters are used to simulate constructor overloading.
Example Code:
typescriptCopy codeclass Car {
make: string;
model: string;
constructor(make: string, model?: string) {
this.make = make;
this.model = model || "Unknown Model";
}
display() {
console.log(`${this.make} - ${this.model}`);
}
}
let car1 = new Car("Toyota");
let car2 = new Car("Honda", "Civic");
car1.display(); // Output: Toyota - Unknown Model
car2.display(); // Output: Honda - Civic
8. Getters and Setters in TypeScript
Definition:
Getters and setters allow controlled access to a class’s properties. Getters are used to retrieve property values, while setters are used to change property values with validation or logic.
Key Features:
- Encapsulates property access and ensures control over how values are accessed or modified.
How it’s Implemented in TypeScript:
TypeScript provides get and set methods to define custom logic for getting and setting property values.
Example Code:
typescriptCopy codeclass User {
private _age: number = 0;
get age(): number {
return this._age;
}
set age(value: number) {
if (value > 0) {
this._age = value;
} else {
console.log("Age must be a positive number.");
}
}
}
let user = new User();
user.age = 25;
console.log(user.age); // Output: 25
user.age = -5; // Output: Age must be a positive number.
These OOP concepts in TypeScript allow developers to write maintainable, reusable, and scalable code by leveraging the strong typing system and advanced object-oriented features of the language.