Method Overriding Lesson

Method overriding happens when a child class defines a method with the same name as a method in the parent class. The child version replaces the parent version for objects created from the child class.

Overriding is useful when the action has the same name but needs different behavior. Every enemy might move, but a walking enemy and a flying enemy should not move the same way.

Code Runner Challenge

Method Overriding Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Method Overriding Lesson

class Enemy {
  move() {
    console.log("The enemy walks forward");
  }
}

class FlyingEnemy extends Enemy {
  move() {
    console.log("The enemy flies over the wall");
  }
}

const enemy = new FlyingEnemy();
enemy.move();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
FlyingEnemy overrides the move method from Enemy. Because the object is a FlyingEnemy, the flying version runs.