Overriding methods
JavaScript · Unit 13: Inheritance
- Full plan
- JavaScript
- 10 exercises
If the child writes a method with the same name as one of the parent's, its objects use the child's: it overrides it. The parent and its own objects don't change.
class Animal {
sound() {
return "...";
}
}
class Dog extends Animal {
sound() {
return "woof";
}
}
console.log(new Animal().sound());
console.log(new Dog().sound());Prints
... woof
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. Predict the output
What does this code print?
2. Complete the code
Fill in the blank so
Squareoverrides the area ofShape, which is always 0.3. Predict the output
What does this code print?
4. Complete the code
A sale item costs 90% of the normal price. Fill in the blank so it uses the price
Productworks out.5. Multiple choice
Vipshould greet likeCustomer, "Hi, Mia", and add " Great to see you!". What goes inside itsgreet()?6. Find the bug
This program should print "Balance: 300 (savings)". Which line has the bug?
7. Predict the output
totalis written inShipping. What does it print?8. Put the lines in order
A donut costs what a bun costs, plus 4. Put the program in order so
Donutadds toBun's cost. TheBunclass fits on one line.9. Find the case that fails
charge(price, off)creates aSaleand returns how much you pay: the price minus the discount, but never less than 0. Which call makes it fail?10. Predict the output
Three music plans, each one a child of the one before. 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.