Function overriding in Javascript
Even though JavaScript is not a classical language that supports classical inheritance and function overriding others do JavaScript does support prototype-based inheritance. Function overriding can be implemented in various ways such as changing the prototypes of objects or by using ES6 classes and the keyword extends.
Below is the implementation of function overriding in Javascript:
class Animal {
makeSound() {
console.log("Animal makes a sound");
}
}
class Dog extends Animal {
makeSound() {
console.log("Dog barks");
}
}
const animal = new Dog();
animal.makeSound(); // Output: Dog barks
Output
Dog barks
Explanation: In JavaScript, you can achieve function overriding using class inheritance. The Dog class extends Animal and provides its own implementation of the makeSound() method. When makeSound() is called on a Dog object, it prints “Dog barks”.
Function overriding in programming
Function Overriding is a fundamental principle in object-oriented programming wherein the subclass implements a specific method that has been declared in the superclass. This concept would enable the method calls to be polymorphic where the same method call may behave differently depending on the object which initiated the method call. In this article, we will discuss the basics of Function Overriding along with its implementation in different languages.
Table of Content
- What is Function overriding?
- Function overriding in C++
- Function overriding in Java
- Function overriding in Python
- Function overriding in C#
- Function overriding in Javascript
- Advantages of Function Overriding
- Disadvantages of Function Overriding