CRT-600 practice question 10 of 30

Refer to the following code block: class Animal{ constructor(name){ this.name = name; } makeSound(){ console.log(`${this.name} is making a sound.`) } } class Dog extends Animal{ constructor(name){ super(name) this.name = name; } makeSound(){ console.log(`${this.name} is barking.`) } } let myDog = new Dog('Puppy'); myDog.makeSound(); What is the console output?

Full set: 223 questions
Answer options
A: Puppy is barking Correct answer
B: Puppy is cracking
Correct Answer:
A. Puppy is barking
Explanation

The code demonstrates class inheritance and method overriding in JavaScript. The Dog class extends the Animal class, inheriting its properties and methods. However, the Dog class provides its own implementation of the makeSound method. When myDog.makeSound() is called on an instance of the Dog class, the JavaScript runtime executes the version of the method defined in the Dog class, not the one in the parent Animal class. This results in the output "Puppy is barking."

Why Incorrect

B. Puppy is cracking: This is incorrect because the string "cracking" is not defined in the makeSound method of either the Dog or Animal class.

References

1. MDN Web Docs: "If there is a method in the subclass that has the same name as a method in the superclass

the method in the subclass will be used."

Source: Mozilla

MDN Web Docs

"Classes - Sub classing with extends". Retrieved from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#subclassingwithextends

2. Eloquent JavaScript (3rd Edition): "When a class extends another class

it inherits its properties and methods. It is also possible to override some of the inherited properties by redefining them."

Source: Haverbeke

M. (2018). Eloquent JavaScript (3rd ed.). No Starch Press. Chapter 6

"The Secret Life of Objects

" section "Classes."

3. JavaScript for Impatient Programmers: "If a subclass defines a method that has the same name as a method in a superclass

the former overrides the latter."

Source: Rauschmayer

A. (2019). JavaScript for Impatient Programmers. Chapter 16

"Classes

" section 16.5.2

"Overriding methods."

Scroll to Top