Skip to the content

Polymorphism

JavaScript · Unit 13: Inheritance

Polymorphism means objects of different classes answer the same method, each in its own way. Whoever uses them doesn't ask which is which: it just calls the method.

Here the loop treats every notice the same, and each one gets sent its own way.

class Notice {
  send(t) {
    return `Notice: ${t}`;
  }
}
class Sms extends Notice {
  send(t) {
    return `SMS: ${t}`;
  }
}
class Email extends Notice {
  send(t) {
    return `Email: ${t}`;
  }
}
const notices = [
  new Sms(),
  new Email(),
];
for (const n of notices) {
  console.log(n.send("Hi"));
}

Prints

SMS: Hi
Email: Hi

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

    Paying by card adds a 10% fee. How much is charged in total?

  3. 3. Predict the output

    What does this code print?

  4. 4. Complete the code

    Fill in the blank to ask whether p is a Payment.

  5. 5. Find the bug

    This program should print true. Which line has the bug?

  6. 6. Predict the output

    Look at the order of the questions. What does it print?

  7. 7. Multiple choice

    Noah wrote this function. Every new animal forces him to add another else if. What does polymorphism suggest?

  8. 8. Predict the output

    NoFunds doesn't define name. What does it print?

  9. 9. Put the lines in order

    Put in order the program that throws a SoldOut error and, when it catches it, prints its message only if it's of that kind.

  10. 10. Predict the output

    The line at the movies. 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 →