Inheritance and Polymorphism
Inheritance Basics
Inheritance lets a class reuse behavior from a parent class and add its own details.
Inheritance Basics
inheritance.ts
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
label(): string {
return this.name;
}
}
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed;
}
summary(): string {
return `${this.label()} is a ${this.breed}`;
}
}
const dogName: string = ;
const dog: Dog = new Dog(dogName, "terrier");
console.log(dog.summary());
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
label(): string {
return this.name;
}
}
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed;
}
summary(): string {
return `${this.label()} is a ${this.breed}`;
}
}
const dogName: string = ;
const dog: Dog = new Dog(dogName, "terrier");
console.log(dog.summary());
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
label(): string {
return this.name;
}
}
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed;
}
summary(): string {
return `${this.label()} is a ${this.breed}`;
}
}
const dogName: string = ;
const dog: Dog = new Dog(dogName, "terrier");
console.log(dog.summary());
extends
`extends` creates a child class that starts with the parent class behavior.