A subclass can inherit properties and methods from a parent class using extends
. The super
keyword is used to call the parent class constructor or methods.
extends
and super()
)When a class extends another class, it automatically gains access to its properties and methods.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak() {
return `${this.name} makes a noise`;
}
}
class Dog extends Animal {
constructor(name: string) {
super(name); // Calls Animal's constructor
}
speak() {
return `${this.name} barks`;
}
}
const dog = new Dog("Buddy");
console.log(dog.speak()); // Buddy barks
Dog
class inherits from Animal
using extends
.constructor
of Dog
must call super(name)
to initialize name
in the parent class.Dog
overrides the speak()
method from Animal
.A subclass can still use parent class methods via super.methodName()
.
class Parent {
greet() {
return "Hello from Parent";
}
}
class Child extends Parent {
greet() {
return super.greet() + " and Child";
}
}
const child = new Child();
console.log(child.greet()); // Hello from Parent and Child
super.greet()
calls the parent class's greet()
method inside Child
.A subclass can override a method but still use the parent method inside.
class Animal {
constructor(public name: string) {}
speak() {
return `${this.name} makes a noise.`;
}
}
class Dog extends Animal {
speak() {
return super.speak() + " But actually, it barks.";
}
}
const dog = new Dog("Charlie");
console.log(dog.speak());
// Charlie makes a noise. But actually, it barks.
super.speak()
calls the original speak()
from Animal
.Dog
class extends and customizes the parent method.If the parent class has getters/setters, the child class can override them and use super
.