DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

What is the method Overriding & Overloading?

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:

  1. 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
Enter fullscreen mode Exit fullscreen mode
  1. 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)
Enter fullscreen mode Exit fullscreen mode

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.

Disclaimer: This article was created with the help of AI.

Top comments (0)