- Classes and Objects:
- Creating classes to model real-world entities:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello(): void {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person = new Person("John Doe", 25);
person.sayHello();
- Defining properties, methods, and constructors within classes:
class Rectangle {
width: number;
height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
const rectangle = new Rectangle(10, 5);
const area = rectangle.getArea();
console.log(`Area: ${area}`);
- Understanding access modifiers (public, private, protected) for encapsulation:
class Car {
private brand: string;
protected year: number;
constructor(brand: string, year: number) {
this.brand = brand;
this.year = year;
}
protected startEngine(): void {
console.log("Engine started.");
}
}
class Sedan extends Car {
drive(): void {
console.log(`Driving a ${this.brand} sedan`);
}
}
const sedan = new Sedan("Honda", 2021);
sedan.drive();
- Implementing inheritance and polymorphism using class inheritance:
class Animal {
makeSound(): void {
console.log("Animal makes sound.");
}
}
class Dog extends Animal {
makeSound(): void {
console.log("Dog barks.");
}
}
const animal: Animal = new Dog();
animal.makeSound();
- Working with abstract classes and interfaces for defining contracts:
abstract class Shape {
abstract getArea(): number;
abstract getPerimeter(): number;
}
class Circle extends Shape {
radius: number;
constructor(radius: number) {
super();
this.radius = radius;
}
getArea(): number {
return Math.PI * this.radius * this.radius;
}
getPerimeter(): number {
return 2 * Math.PI * this.radius;
}
}
const circle: Shape = new Circle(5);
const area = circle.getArea();
const perimeter = circle.getPerimeter();