Skip to the content

Overriding methods

JavaScript · Unit 13: Inheritance

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. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank so Square overrides the area of Shape, which is always 0.

  3. 3. Predict the output

    What does this code print?

  4. 4. Complete the code

    A sale item costs 90% of the normal price. Fill in the blank so it uses the price Product works out.

  5. 5. Multiple choice

    Vip should greet like Customer, "Hi, Mia", and add " Great to see you!". What goes inside its greet()?

  6. 6. Find the bug

    This program should print "Balance: 300 (savings)". Which line has the bug?

  7. 7. Predict the output

    total is written in Shipping. What does it print?

  8. 8. Put the lines in order

    A donut costs what a bun costs, plus 4. Put the program in order so Donut adds to Bun's cost. The Bun class fits on one line.

  9. 9. Find the case that fails

    charge(price, off) creates a Sale and returns how much you pay: the price minus the discount, but never less than 0. Which call makes it fail?

  10. 10. Predict the output

    Three music plans, each one a child of the one before. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →