📘
Classes and Object-Oriented Programming
Beginner
100 XP
40 min
Lesson Content
Classes in TypeScript
TypeScript classes support access modifiers and are essential for Angular and object-oriented programming.
Basic Class
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hello, I'm ${this.name}`;
}
}Access Modifiers
class BankAccount {
public balance: number; // Accessible everywhere
private accountNumber: string; // Only inside class
protected owner: string; // Accessible in subclasses
}Inheritance
class Animal {
constructor(public name: string) {}
speak(): void {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
speak(): void {
console.log(`${this.name} barks`);
}
}Example Code
Create classes with properties and methods
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 rect = new Rectangle(5, 10);
console.log(`Area: ${rect.getArea()}`);Expected Output:
Area: 50
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code