#typescript
#oop
#inheritance
Day 10: Inheritance and Abstract Classes
Building on Foundations
Welcome to Day 10! Today we unlock the real power of OOP: Inheritance.
Inheritance (extends)
Inheritance allows a class (Child) to acquire properties and methods from another class (Parent).
class Animal {
move(distance: number = 0) {
console.log(`Animal moved ${distance}m.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog();
dog.bark(); // "Woof! Woof!"
dog.move(10); // "Animal moved 10m." (Inherited!)
Overriding Methods
A child class can replace a parent’s method. You can still access the parent’s method using super.
class Snake extends Animal {
move(distance: number = 5) {
console.log("Slithering...");
super.move(distance);
}
}
Protected Members
Remember protected from yesterday?
private: Only visible in the class.protected: Visible in the class and subclasses.
class Person {
protected name: string;
constructor(name: string) { this.name = name; }
}
class Employee extends Person {
private department: string;
constructor(name: string, dept: string) {
super(name); // Must call super() first!
this.department = dept;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
Abstract Classes
An abstract class is a base class that cannot be instantiated directly. It serves as a blueprint for other classes.
abstract class Department {
constructor(public name: string) {}
printName(): void {
console.log("Department name: " + this.name);
}
// Abstract methods MUST be implemented by derived classes
abstract printMeeting(): void;
}
// const d = new Department(); // Error: Cannot create an instance of an abstract class.
class AccountingDepartment extends Department {
printMeeting(): void {
console.log("The Accounting Department meets each Monday at 10am.");
}
}
Challenge for Today
- Create an abstract class
Shapewith an abstract methodgetArea(): number. - Create two classes
RectangleandCirclethat extendShape. - Implement
getAreafor both (Rectangle: width * height, Circle: PI * r^2). - Create a function
printArea(shape: Shape)that works with either.
See you on Day 11 for Static Members and Accessors!