Inheritance
Inheritance allows classes to inherit properties and methods from parent classes, promoting code reuse and establishing hierarchies.
Basic Inheritance
Output
Click Run to execute your code
Key Concepts:
extends- Creates inheritance relationshipsuper()- Calls parent constructor- Child inherits ALL parent members
- Can override parent methods
Method Overriding
Child classes can override parent methods to provide specific behavior:
class Animal {
makeSound(): void {
console.log("Generic sound");
}
}
class Cat extends Animal {
makeSound(): void { // Override
console.log("Meow!");
}
}
let cat = new Cat();
cat.makeSound(); // "Meow!"
Common Mistakes
1. Forgetting super() in Constructor
class Animal {
constructor(public nameAnimal: string) {}
}
class Dog extends Animal {
constructor(nameAnimal: string, public breed: string) {
// โ Error - must call super() first!
this.breed = breed;
}
}
// โ Correct
class Dog extends Animal {
constructor(nameAnimal: string, public breed: string) {
super(nameAnimal); // Call parent first
this.breed = breed;
}
}
2. Accessing Private Parent Members
class Parent {
private secret = "hidden";
}
class Child extends Parent {
reveal() {
console.log(this.secret); // โ Error! Private
}
}
// โ Use protected instead
class Parent {
protected secret = "hidden";
}
Best Practice: Favor composition over deep
inheritance hierarchies. Keep hierarchies shallow (2-3 levels max).
Summary
- Use
extendsfor inheritance - Call
super()in child constructor - Child inherits all parent members
- Override methods for specific behavior
- Use
protectedfor inheritance-friendly members
Enjoying these tutorials?