Method overriding and method overloading are two important concepts in object-oriented programming, including JavaScript. Let's discuss each concept and provide examples in JavaScript:
- Method Overriding:
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. This allows a subclass to provide a specialized implementation of a method that is already defined in its superclass.
Example in JavaScript:
class Animal {
sound() {
console.log("Animal makes a sound");
}
}
class Dog extends Animal {
sound() {
console.log("Dog barks");
}
}
const animal = new Animal();
const dog = new Dog();
animal.sound(); // Output: Animal makes a sound
dog.sound(); // Output: Dog barks
- Method Overloading:
Method overloading refers to defining multiple methods with the same name but with different parameters or different number of parameters. This allows a single method name to perform different tasks based on the parameters passed to it.
JavaScript does not support method overloading directly because it does not have method signatures. However, you can simulate method overloading by checking the number of arguments or the types of arguments within a function.
Example in JavaScript:
class Calculator {
add(a, b) {
if (typeof b === 'undefined') {
// Method overloading for one argument
return a + a;
} else {
// Method overloading for two arguments
return a + b;
}
}
}
const calculator = new Calculator();
console.log(calculator.add(5, 3)); // Output: 8
console.log(calculator.add(5)); // Output: 10 (overloaded method)
In the above example, the add method is overloaded to handle both one argument (doubling the value) and two arguments (adding the values together). The method implementation checks the number of arguments to determine which operation to perform.
Support My Work โค๏ธ
If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!
Connect with Me ๐
Letโs stay connected! You can follow me or reach out on these platforms:
๐น YouTube โ Tutorials, insights & tech content
๐น LinkedIn โ Professional updates & networking
๐น GitHub โ My open-source projects & contributions
๐น Instagram โ Behind-the-scenes & personal updates
๐น X (formerly Twitter) โ Quick thoughts & tech discussions
Iโd love to hear from youโwhether itโs feedback, collaboration ideas, or just a friendly hello!
Disclaimer
This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.
Top comments (0)