Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Method Overloading and Overriding in Java

Last Updated on April 10, 2023 by Prepbytes

Method Overloading and Overriding in Java are two important concepts that help in enabling the object-oriented feature of Java. Both of these features are important as they help in creating methods that can perform multiple tasks with the same name. In this tutorial, we will go through Method Overloading and Overriding in Java in depth, with examples of both.

Method or Function Overloading in Java

Method Overloading in Java is defined as the ability to create methods with the same name but with different types of parameters. Method Overloading helps the developer in achieving Compile Time Polymorphism in Java.

Example of Method Overloading in Java

This example will help you in a better understanding of the “Method Overloading in Java”

Code:

class Calculator {
    
    // Method to add two integers
    public int add(int x, int y) {
        return x + y;
    }
    
    // Method to add two doubles
    public double add(double x, double y) {
        return x + y;
    }
    
    // Method to add three integers
    public int add(int x, int y, int z) {
        return x + y + z;
    }
}

public class Main{
    public static void main(String args[]){
        Calculator calc = new Calculator();

        int result1 = calc.add(2, 3);  
          System.out.println(result1);
     
        double result2 = calc.add(2.5, 3.5);
        System.out.println(result2);

        int result3 = calc.add(2, 3, 4);    
        System.out.println(result3);

    }
}

Output:

5
6.0
9

Explanation:
In the above code, in the Calculator class we have defined three methods with the same name i.e., add, but each with different types of parameters.

  • The first method takes two integers as input and returns their sum.
  • The second method takes two doubles as input and returns their sum.
  • The third method takes three integers as input and returns their sum.

In the main method, we call the add method with different parameters. For each call, the JVM automatically chooses the appropriate method based on the parameters passed to it and we get the expected output on the screen.

Method Overriding in Java

Method Overriding in Java is defined as the feature which allows Java developers to create new implementations for the methods that already exist in the parent class. This is done by defining a method in the child class with the same name and the same signature in the parent class.

Example of Method Overriding in Java

Method Overriding in Java is demonstrated with the help of the example given below.

Code:

class Animal {
    
    public void speak() {
        System.out.println("The animal makes a sound");
    }
}

class Cat extends Animal {
    
    @Override
    public void speak() {
        System.out.println("Meow!");
    }
}

class Dog extends Animal {
    
    @Override
    public void speak() {
        System.out.println("Woof!");
    }
}

public class Main{
    public static void main(String args[]){
        Animal animal1 = new Animal();
        Animal animal2 = new Cat();
        Animal animal3 = new Dog();
        
        animal1.speak(); 
        animal2.speak(); 
        animal3.speak(); 

    }
}

Output:

The animal makes a sound
Meow!
Woof!

Explanation:
In the above example, we have a superclass called "Animal" with a method called "speak". We have two subclasses called "Cat" and "Dog" that inherit from the "Animal" class. Both the "Cat" and "Dog" classes have their own implementation of the "speak" method using the @Override annotation.

When we call the "speak" method on an object of the "Cat" or "Dog" class, Java will use the implementation in the subclass instead of the implementation in the superclass. In the above example, when we call the "speak" method on the "animal1" object, Java uses the implementation in the superclass, and prints "The animal makes a sound". When we use the "speak" method on the "animal2" object, Java utilizes the "Cat" subclass implementation and outputs "Meow!". Similarly, when we call the "speak" method on the "animal3" object, Java uses the implementation in the "Dog" subclass, and prints "Woof!".

Method Overloading vs Method Overriding in Java

Method overloading and method overriding are two different concepts, but they are often confused with each other. The key difference between them is that method overloading is used to create multiple methods with the same name but with different parameters, while Method overriding is used in a subclass to create a new implementation of an existing method.

Here are the key differences between the Method Overloading and Overriding in Java.

Method Overloading Method Overriding
Multiple methods with the same name can exist within a class. A new implementation of an existing method can exist in a subclass.
The methods must have a different number or types of parameters. The method must have the same name, return type, and parameter list as the overridden method in the superclass.
Java automatically chooses the appropriate method based on the parameters passed to it. Java uses the implementation in the subclass instead of the implementation in the superclass.
Overloading can be done in the same class or in a subclass. Overriding can only be done in a subclass that inherits from the superclass.

Example of Method Overloading and Overriding in Java in a Single Program

Let’s take an example to illustrate the difference between method overloading and method overriding in a single code.

Code:

class Animal {
    
    public void speak() {
        System.out.println("The animal makes a sound");
    }
    
    public void speak(String language) {
        System.out.println("The animal speaks " + language);
    }
}

class Cat extends Animal {
    
    @Override
    public void speak() {
        System.out.println("Meow!");
    }
    
    public void speak(int numTimes) {
        for (int i = 0; i < numTimes; i++) {
            System.out.print("Meow! ");
        }
    }
}

public class Main {
    
    public static void main(String[] args) {
        Animal animal1 = new Animal();
        Cat animal2 = new Cat();
        
        animal1.speak();          // The animal makes a sound
        animal1.speak("French");  // The animal speaks French
        
        animal2.speak();          // Meow!
        animal2.speak(3);         // Meow! Meow! Meow!
    }
}

Output:

The animal makes a sound
The animal speaks French
Meow!
Meow! Meow! Meow!

Explanation:
In the above examples, we have a Cat subclass that inherits from the Animal class. The Cat class overrides the speak() method of the Animal class and offers its own implementation that prints Meow! The Cat class also has its own speak method, which takes an integer input called numTimes and prints Meow! multiple times based on the number of numTimes.

In the main method, we create two objects: one of the "Animal" class and one of the "Cat" class. Then the following statements were executed.

  • When we call the "speak" method on the "animal1" object, Java uses the implementation in the superclass and prints "The animal makes a sound".
  • When we call the "speak" method on the "animal1" object with the string argument "French", Java uses the second method in the superclass and prints "The animal speaks French".
  • We get the output Meow! when we call the speak method of the animal 2 object using the cat subclass.
  • Java uses the second method in the subclass cat when we give 3 as the parameter to the animal 2 object as a result we get the output Meow! printed three times.

Conclusion
Method overloading and method overriding are two important concepts in Java that every programmer should understand. Method overloading allows us to create multiple methods with the same name but with different parameters, while method overriding allows us to create a new implementation of an existing method in a subclass. In method overloading, Java automatically chooses the appropriate method based on the parameters passed to it. In method overriding, Java uses the implementation in the subclass instead of the implementation in the superclass.

Frequently Asked Questions (FAQs)

Here are some Frequently Asked Questions on Method Overloading and Overriding in Java.

Ques 1. Can we overload static methods in Java?
Ans. Yes, the static methods in Java can be overloaded.

Ques 2. Enlist the differences between method overloading and constructor overloading In Java.
Ans. Method overloading in Java allows us to create multiple methods with the same name but with different parameters, while constructor overloading allows us to create multiple constructors with different parameters.

Ques 3. Can we override static method in Java?
Ans. No, we cannot override static methods in Java.

Ques 4. What is dynamic method dispatch in Java?
Ans. Dynamic method dispatch is a feature in Java that allows the JVM to determine which implementation of an overridden method to use at runtime.

Ques 5. Can we override constructors in Java?
Ans. No, we cannot override constructors in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *