0
0
Javascriptprogramming~10 mins

Inheritance using classes in Javascript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Inheritance using classes
Define Parent Class
Define Child Class extends Parent
Create Child Object
Access Child Method
Access Parent Method via Child
Use Child and Parent Properties
Inheritance lets a child class use properties and methods from a parent class, sharing and extending behavior.
Execution Sample
Javascript
class Animal {
  speak() {
    return 'Animal speaks';
  }
}
class Dog extends Animal {
  speak() {
    return 'Dog barks';
  }
}
const pet = new Dog();
console.log(pet.speak());
This code shows a Dog class inheriting from Animal and overriding the speak method.
Execution Table
StepActionEvaluationResult
1Define class Animal with method speakAnimal.speak() returns 'Animal speaks'Animal class ready
2Define class Dog extends Animal with method speakDog.speak() returns 'Dog barks'Dog class ready, inherits Animal
3Create new Dog object petpet is instance of Dogpet created
4Call pet.speak()Dog's speak method overrides Animal's'Dog barks' returned
5If Dog did not override speak, Animal's speak would runNot applicable hereN/A
💡 Execution ends after pet.speak() returns 'Dog barks'
Variable Tracker
VariableStartAfter Step 3After Step 4Final
petundefinedDog instance createdpet.speak() method calledpet remains Dog instance
Key Moments - 2 Insights
Why does pet.speak() call Dog's method, not Animal's?
Because Dog class overrides speak(), so pet uses Dog's version (see execution_table step 4).
What if Dog did not have speak() method?
Then pet.speak() would use Animal's speak() method inherited (see execution_table step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what does pet.speak() return at step 4?
A'Animal speaks'
Bundefined
C'Dog barks'
DError
💡 Hint
Check execution_table row with Step 4 for pet.speak() result
At which step is the Dog object created?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at execution_table row describing object creation
If Dog did not override speak(), what would pet.speak() return?
A'Animal speaks'
Bundefined
C'Dog barks'
DError
💡 Hint
See execution_table step 5 about inherited method usage
Concept Snapshot
class Parent {
  method() {}
}
class Child extends Parent {
  method() {} // overrides
}
const obj = new Child();
obj.method() calls Child's method if overridden,
otherwise Parent's method.
Full Transcript
Inheritance in JavaScript classes means a child class can use and override methods from a parent class. First, we define a parent class Animal with a speak method. Then, we define a Dog class that extends Animal and overrides speak. When we create a Dog object pet and call pet.speak(), it uses Dog's speak method, not Animal's. If Dog did not override speak, pet.speak() would use Animal's method. This shows how inheritance shares behavior but allows customization.