Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Overriding Methods in Subclasses | Inheritance and Encapsulation
JavaScript Classes and OOP Foundations

bookOverriding 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.

1234567891011121314151617
class 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.
copy
question mark

Why would you override a method in a subclass instead of using the parent class's version?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 3

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Awesome!

Completion rate improved to 6.25

bookOverriding Methods in Subclasses

Deslize para mostrar o menu

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.

1234567891011121314151617
class 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.
copy
question mark

Why would you override a method in a subclass instead of using the parent class's version?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 3
some-alt