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.
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme
Awesome!
Completion rate improved to 5
Method Overriding and super
Pyyhkäise näyttääksesi valikon
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.
Kiitos palautteestasi!