Start learning free

LESSON 637 OF 675 · OBJECT-ORIENTED PROGRAMMING

Method Overriding in TypeScript

Lesson

TL ; DR:

When a child class defines a method with the same name as the parent's, the child's version overrides the parent's. Different objects can give the same method name different behavior.


class Dog {
    bark() { console.log("Woof!"); }
}
class Puppy extends Dog {
    bark() { console.log("Yip!"); }
}


Full lesson:

You've seen that a child class inherits the parent's methods. Overriding is what happens when the child wants to change one of those inherited methods.

Why override?

Subclasses are usually special cases of the parent. A Puppy is a Dog, but it sounds different — "Yip!" instead of "Woof!". Instead of inventing a new method name, you redefine bark() on the Puppy. Callers don't need to know which subclass they're holding — they just call bark() and the right version runs.

How it works in TypeScript

  • Every method can be overridden: define a method with the same name in the child class and it wins. No keyword is required on the parent or the child.
  • TypeScript also has an optional override modifier (override bark(): void { ... }). It makes the compiler check that the parent really has a method with that name. This lesson doesn't need it.
  • The method keeps the same name and compatible parameter and return types, so callers can use either class the same way.

Your task

The Dog class already defines bark. Inside the Puppy subclass, override bark so it prints "Yip! I am " followed by the puppy's name. The harness creates a Puppy named "Buddy" and calls bark() on it.

Expected output:

Yip! I am Buddy
STEP 1 OF 2
    Ctrl + Enter to check