Class Inheritance in JavaScript
Level 5332 keystrokes
This demonstrates class inheritance with extends and super, and method overriding.
JavaScript code
// Base class (parent class)1class Animal { // Constructor initializes instance properties2 constructor(name) {3 this.name = name;4 }5 // Method that can be overridden by subclasses6 speak() {7 console.log(`${this.name} makes a sound.`);8 }9}10 // Derived class (child class) extends Animal// It inherits all properties and methods from Animal11class Dog extends Animal { // Dog's constructor takes additional parameter12 constructor(name, breed) { // super() calls the parent constructor // Must be called before using 'this'13 super(name); // Add Dog-specific property14 this.breed = breed;15 }16 // Override the parent's speak method // This replaces Animal's speak for Dog instances17 speak() {18 console.log(`${this.name} barks!`);19 }20}21 // Create a Dog instance22const dog = new Dog("Buddy", "Golden");// Calls Dog's overridden speak method23dog.speak();// Access Dog-specific property24console.log(dog.breed);Output
Buddy barks! Golden
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
.× 10(× 10)× 10;× 8{× 8}× 8"× 4`× 4=× 3,× 2