Overriding Methods in Subclasses
When working with classes in JavaScript, you often want subclasses to behave differently from their parent classes in certain situations. Method overriding allows you to redefine a method in a subclass, providing specialized behavior while keeping the same method name. This is a key feature of object-oriented programming and helps you create flexible and reusable code structures. By overriding a method, the subclass version is called instead of the parent's version when you use that method on an instance of the subclass. This is especially useful when the subclass represents a more specific concept that needs to act differently from the general parent class.
1234567891011121314151617class Animal { speak() { console.log("The animal makes a sound."); } } class Dog extends Animal { speak() { console.log("The dog barks."); } } const genericAnimal = new Animal(); genericAnimal.speak(); // The animal makes a sound. const myDog = new Dog(); myDog.speak(); // The dog barks.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you explain how method overriding works in this example?
What happens if the subclass does not override the method?
Can you show an example with more subclasses?
Awesome!
Completion rate improved to 6.25
Overriding Methods in Subclasses
Свайпніть щоб показати меню
When working with classes in JavaScript, you often want subclasses to behave differently from their parent classes in certain situations. Method overriding allows you to redefine a method in a subclass, providing specialized behavior while keeping the same method name. This is a key feature of object-oriented programming and helps you create flexible and reusable code structures. By overriding a method, the subclass version is called instead of the parent's version when you use that method on an instance of the subclass. This is especially useful when the subclass represents a more specific concept that needs to act differently from the general parent class.
1234567891011121314151617class Animal { speak() { console.log("The animal makes a sound."); } } class Dog extends Animal { speak() { console.log("The dog barks."); } } const genericAnimal = new Animal(); genericAnimal.speak(); // The animal makes a sound. const myDog = new Dog(); myDog.speak(); // The dog barks.
Дякуємо за ваш відгук!