Method Overloading And Overriding In Java (With example)

Method Overloading And Overriding In Java (With example)

25 Sep 2024
Beginner
1.66K Views
12 min read
Learn with an interactive course and practical hands-on labs

Java Online Course Free with Certificate

Method Overloading Vs. Overriding In Java

Overloading and Overriding are two basic ideas that are different in several various ways in Java. Compile-time polymorphism is achieved by overloading, which allows multiple methods inside the same class to have the same name but different parameters (type, number, or both). On the other hand, overriding offers runtime polymorphism when a subclass offers a particular implementation of a method that is already specified in its superclass.

In this Java tutorial, we will explore more about Overloading and Overriding in Java and we are going to more focus on the difference between method overloading and overriding In Java. So let's understand first what is method overriding and what is method overloading.

Take the leap into full stack development—join our Java Full Stack Developer Training for expert guidance.

What is Method Overriding in Java?

  • In method overriding a subclass can override a method that is specified in its superclass by providing a customized implementation.
  • It makes polymorphism in Java possible by allowing a subclass to specify its own implementation of a function.
  • One kind of runtime polymorphism is method overriding.
  • Method overriding is the process of giving a method in a derived class the same name, parameters, and return type as a method in the parent class.
  • For a method that is already defined in the parent class, the derived class offers a particular implementation.

Key Characteristics

  • Inheritance Requirement: A superclass-subclass relationship is necessary for overriding.
  • Same Method Signature: The name, parameters, and return type of overriding methods are all the same.
  • Runtime Polymorphism: The object type determines at runtime which method should be used.

Examples of Method Overriding

// Superclass
class Company {
    void NoofEmployees() {
        System.out.println("Number of Employees");
    }
}
// Subclass overriding method
class Employee extends Company {
    @Override
    void NoofEmployees() {
        System.out.println("There are 50 employees");
    }
}
// Main class to demonstrate method overriding
public class Main {
    public static void main(String[] args) {
        Company comp = new Company(); // Create Company object
        comp.NoofEmployees(); // Output: NumberofEmployees
        
        Company emp = new Employee(); // Company reference but Dog object
        emp.NoofEmployees(); // Output: There are 50 employees
    }
}

Output

NumberofEmployees
There are 50 employees

Explanation

  • Company Class: This is the superclass with a method NoofEmployees() that prints "Number of Employees".
  • Employee Class: Extends Company and overrides the NoofEmployees() method to print " There are 50 employees" instead.
  • Main Class: In the main method: A Company object ( comp) calls NoofEmployees(), which prints "Number of Employees".
  • An Employee object is assigned a reference of type Company ( employee). When employee. NoofEmployees() is called, it dynamically binds to the NoofEmployees() method in the Employee class due to method overriding, printing " There are 50 employees."

Usage

  • Used in inheritance to implement certain behaviors in subclasses.
  • It offers specific implementations of the methods used by abstract classes or interfaces.

What is Method Overloading in Java?

  • The ability to define multiple methods with the same name but different parameters in a class is known as method overloading in Java.
  • These techniques improve the flexibility and clarity of the code by accomplishing comparable tasks with different inputs.
  • Compile time polymorphisms include method overloading.
  • Although the return type of the method may or may not remain the same, in Java, you can not achieve method overloading by changing only the return type of the method.

Key Characteristics

  • Same Method Name: The names of the overloading methods are the same.
  • Different Parameters: Parameters might be different in terms of their type, number, or both.
  • Compile Time Resolution: The method signature is used to determine how overloading is resolved at build time.

Examples of Method Overloading

public class Calculator {

    // Method to add two integers
    public int add(int a, int b) {
        return a + b;
    }

    // Method to add three integers
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    // Method to add two doubles
    public double add(double a, double b) {
        return a + b;
    }

    // Method to concatenate two strings
    public String add(String a, String b) {
        return a + b;
    }

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

        // Calling different overloaded methods
        int sum1 = calc.add(5, 10);
        int sum2 = calc.add(5, 10, 15);
        double sum3 = calc.add(2.5, 3.5);
        String concatenatedString = calc.add("Hello, ", "World!");

        // Displaying results
        System.out.println("Sum of integers (5 + 10): " + sum1);
        System.out.println("Sum of integers (5 + 10 + 15): " + sum2);
        System.out.println("Sum of doubles (2.5 + 3.5): " + sum3);
        System.out.println("Concatenated string: " + concatenatedString);
    }
}

Output

Sum of integers (5 + 10): 15
Sum of integers (5 + 10 + 15): 30
Sum of doubles (2.5 + 3.5): 6.0
Concatenated string: Hello, World!

Explanation

In this instance:

The Calculator class defines multiple add methods with different parameters but the same name.
  • Two integers are added using add(int a, int b).
  • Three integers are added with add(int a, int b, int c).
  • Two doubles are added using add(double a, double b).
  • Two strings are concatenated with add(String a, String b).
The main function calls several overloaded add methods with the proper inputs, and the System is used to display the results. Printout.

Usage

  • It provides several methods (such as add(int, int) and add(double, double)) for calling a method with various parameter types.
  • It is used to define constructors for object initialization that take distinct argument lists.

Differences Between Overloading and Overriding in Java

First, let's see the main difference between Java's method overloading and overriding.In Java, the primary difference between method overriding and overloading is that:
When two or more methods in a class have the same name but distinct parameters, this is known as overloading. This enables us to offer various implementations of the same procedure for various data types or argument counts. Compile-time polymorphisms like overloading exist.

Differences Between Overloading and Overriding

On the other hand, overriding happens when a subclass implements a method that is already specified in the superclass. This enables us to modify the behavior of the method specifically for the subclass. During runtime, overriding is a polymorphism.
I also have mentioned a list of more differences between method overloading and method overriding as follow:
Method Overloading in JavaMethod Overriding in Java
It is a compile-time polymorphism.It is a run-time polymorphism.
It helps to increase the readability of the program.It is used to give access to the specific implementation of the method which is already provided by its parent class or superclass.
Method overloading occurs within the class only.Method overriding is performed in two classes with inheritance relationships.
It may or may not require inheritance.It always needs inheritance.
In this, methods must have the same name and different characteristicsIn this, methods must have the same name and same characteristics.
In this, the return type can or can not be the same, but you have to change the parameter.In this, the return type must be the same or co-variant.
Static binding is used in method overloading.In method overriding dynamic binding is used.
In this, Private and final methods can be overloaded.In this, private and final methods can’t be overridden.
The parameters should be different while doing method overloading.The parameters should be the same in method overriding.
Conclusion
Effective object-oriented programming requires an understanding of the differences between Java's overloading and overriding methods. While overriding enables runtime polymorphism and behavior customization in subclasses, overloading permits method variety and code clarity within a class. Java developers can use inheritance and abstraction to create reliable and maintainable software by grasping these ideas. However, if you want to master in these concepts you can join our Java Full Stack Training. Also, I would like to listen to your feedback on this informative article. Enjoy coding..!

FAQs

Java differentiates between overloaded methods by examining the method signatures, which include the method name and the number, type, and order of parameters. 

 No, static methods cannot be overridden in Java. They belong to the class rather than instances, so they are hidden, not overridden when redefined in a subclass. 

The main purpose of method overloading is to enhance code readability and flexibility by allowing multiple methods with the same name to perform similar tasks with different input parameters. 

The main purpose of method overriding is to allow a subclass to provide a specific implementation of a method already defined in its superclass, enabling runtime polymorphism and behavior customization. 
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this