Classes and OOP · Lesson 28 of 45
Inheritance
A class that takes everything from another and adds more.
8 minutes3 games
With extends a new class inherits every property and method of another (the parent), then adds or changes things. Inside its constructor you must call super(...) first so the parent sets up its part.
JavaScript
class User {
constructor(name) {
this.name = name
}
describe() {
return `${this.name} is a user`
}
}
class Instructor extends User {
constructor(name, subject) {
super(name)
this.subject = subject
}
describe() {
return `${super.describe()} who teaches ${this.subject}`
}
}
const people = [new User("Ali"), new Instructor("Sara", "JavaScript")]
for (const p of people) console.log(p.describe())
console.log(people[1] instanceof User)- User
- name
- describe()
- Instructor extends User
- subject
- describe() (overridden)
What's the output?
class A {
hi() {
return "A"
}
}
class B extends A {
hi() {
return "B" + super.hi()
}
}
console.log(new B().hi())What will this code print?
Spot the bug
One line throws an error. Which?
Exercise
Make Square extends Rectangle taking just side. Print new Square(6).area() (36).
Expected output: 36
JavaScript
class Rectangle {
constructor(w, h) {
this.w = w
this.h = h
}
area() {
return this.w * this.h
}
}
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.