extends
JavaScript · Unit 13: Inheritance
- Full plan
- JavaScript
- 10 exercises
Sometimes a class is a more specific version of another: a dog is an animal. With extends, the child class gets everything from the parent class without copying it: its constructor and its methods.
Dog writes nothing between its braces, and it can still eat.
class Animal {
constructor(name) {
this.name = name;
}
eat() {
return `${this.name} eats`;
}
}
class Dog extends Animal {}
const rex = new Dog("Rex");
console.log(rex.eat());Prints
Rex eats
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Complete the code
Fill in the blank so
Scooteris a child class ofVehicle.2. Predict the output
What does this code print?
3. Multiple choice
Savingswas written like this:class Savings extends Account {}. What does an object made withnew Savings(100)have?4. Predict the output
What does this code print?
5. Predict the output
CatandDogare children of the same parent. What does it print?6. Find the bug
This program should print "Rayo drifts". Which line has the bug?
7. Predict the output
What does this code print?
8. Put the lines in order
Put the program in order so Kira, a
Cat, introduces herself with the method she inherits fromPet.9. Multiple choice
A store's program has an
Employeeclass. Which one makes sense as a child class ofEmployee?10. Predict the output
Some products in the cart are on sale. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.