Method Overriding and super
123456789101112131415161718class Animal { makeSound() { console.log("Some generic animal sound"); } } class Dog extends Animal { makeSound() { super.makeSound(); console.log("Woof!"); } } const myDog = new Dog(); myDog.makeSound(); // Output: // Some generic animal sound // Woof!
When you create a derived class in TypeScript, you can override methods from the base class to change or extend their behavior. This is called method overriding. To override a method, you simply define a method with the same name in the derived class. If you want to use the original implementation from the base class as part of your new method, you can call it using the super keyword. The super keyword refers to the parent class and allows you to access its methods or constructor.
By calling super.methodName(), you can invoke the base class version of a method before or after adding extra logic in your derived class. This is especially useful when you want to extend the functionality rather than completely replace it. Overriding methods and using super helps you build flexible and maintainable class hierarchies, where shared behavior is defined once in a base class, and specialized behavior is added in derived classes.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Can you explain more about how method overriding works in TypeScript?
What happens if I don't use the super keyword in the derived class?
Can you give another example of method overriding with different classes?
Awesome!
Completion rate improved to 5
Method Overriding and super
Sveip for å vise menyen
123456789101112131415161718class Animal { makeSound() { console.log("Some generic animal sound"); } } class Dog extends Animal { makeSound() { super.makeSound(); console.log("Woof!"); } } const myDog = new Dog(); myDog.makeSound(); // Output: // Some generic animal sound // Woof!
When you create a derived class in TypeScript, you can override methods from the base class to change or extend their behavior. This is called method overriding. To override a method, you simply define a method with the same name in the derived class. If you want to use the original implementation from the base class as part of your new method, you can call it using the super keyword. The super keyword refers to the parent class and allows you to access its methods or constructor.
By calling super.methodName(), you can invoke the base class version of a method before or after adding extra logic in your derived class. This is especially useful when you want to extend the functionality rather than completely replace it. Overriding methods and using super helps you build flexible and maintainable class hierarchies, where shared behavior is defined once in a base class, and specialized behavior is added in derived classes.
Takk for tilbakemeldingene dine!