Navratri Sale: Get Upto 30% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Method Overloading in Java

Method Overloading in Java

10 Sep 2024
Beginner
220 Views
34 min read
Learn via Video Course & by Doing Hands-on Labs

Java Online Course Free with Certificate (2024)

Understanding Method Overloading in Java

Understanding method overloading in Java is important for learning its object-oriented programming capabilities. Method Overloading enables you to declare multiple methods with the same name but distinct parameters, resulting in different implementations depending on the input. This makes your code simpler and more manageable because you may use the same method name for many tasks.

In this Java tutorial, we will look at method overloading in Java and cover what it is. And when should we utilize method overloading? We'll also look at Method Overloading in Java with examples. So, let us begin by examining "What is Method Overloading?"

Start coding with confidence—join our Java Full Stack Developer Course Training and gain hands-on experience.

What is Method Overloading?

  • Method Overloading in Java lets you create several methods with the same name but different parameters.
  • This means you can have multiple methods that do similar tasks, but each works with different types or numbers of inputs.
  • It makes your code easier to understand and use because you can call the same method name in different situations.

For example, method overloading is when a calculated method can compute the area of different shapes, such as a circle (using radius) or a rectangle (using length and width), by using the same method name with different parameters.

Why is Method Overloading Important?

  • Method Overloading is important because it lets you use the same method name for similar tasks but with different inputs.
  • This makes your code cleaner and easier to understand, and it avoids repeating code.
  • It also helps handle different scenarios without needing extra method names.

Advantages of Method Overloading

  • Method overloading improves the readability and reusability of the code.
  • Method overloading decreases the program's complexity.
  • Method overloading allows programmers to complete a task efficiently and effectively.
  • Method overloading allows you to access methods that perform related functions but use slightly different arguments and types.
  • Objects of a class can also be initialized in various ways using constructors.

Different Ways to Implement Method Overloading

Here are various techniques to implement method overloading.

1. Changing the Number of Parameters

  • One of the simplest ways to implement method overloading is by changing the number of parameters.
  • A method may vary depending on how many parameters are supplied.
  • The following example demonstrates how to implement method overloading with varying numbers of parameters in method declaration and definition.

Example

class Calculator {
    // Method to sum two integers
    int sum(int a, int b) {
        return a + b;
    }

    // Overloaded method to sum three integers
    int sum(int a, int b, int c) {
        return a + b + c;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println("Sum of 2 numbers: " + calc.sum(10, 20)); // Output: 30
        System.out.println("Sum of 3 numbers: " + calc.sum(10, 20, 30)); // Output: 60
    }
}

Output

Sum of 2 numbers: 30
Sum of 3 numbers: 60

Explanation

  • The overloaded methods in the Calculator class are both named sum(). One takes two integer parameters, whereas the other method takes three.
  • The first sum() method is responsible for calculating the addition of two integers, and the second is for three integers.
  • In the main method, an object of the class Calculator is created, and the sum() the method is invoked in two ways: first with two arguments, which gives the sum of these two integers, and second with three arguments, which returns the sum of all three integers.
  • The program then outputs the results, thus showing the principle of method overloading in Java.

Real-Life Example

class ShoppingCart {
    // Method to calculate total cost without discount
    double calculateTotal(double price1, double price2) {
        return price1 + price2;
    }

    // Overloaded method to calculate total cost with a discount on one item
    double calculateTotal(double price1, double price2, double discount) {
        return price1 + (price2 - discount);
    }
}

public class Main {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
        System.out.println("Total cost without discount: " + cart.calculateTotal(50.0, 30.0)); // Output: 80.0
        System.out.println("Total cost with discount: " + cart.calculateTotal(50.0, 30.0, 5.0)); // Output: 75.0
    }
}

Output

Total cost without discount: 80.0
Total cost with discount: 75.0

Explanation

  • The ShoppingCartthe class has two overloaded methods named calculateTotal(). One method calculates the total cost of two items without any discount, while the other method calculates the total cost with a discount applied to one of the items.
  • The first calculateTotal() method simply adds the prices of the two items. The second calculateTotal() method subtracts the discount from the price of one item before adding the two prices.
  • In the Main method, an instanceShoppingCart is created. The calculateTotal()the method is called twice: once without a discount and once with a discount, demonstrating method overloading.
  • The program prints the results, showing how the total cost changes based on whether a discount is applied or not.

2. Changing the Data Type of Parameters

One more way to perform method overloading is to change the data types of method parameters. The following example demonstrates how to perform method overloading in method declaration and definition using various parameter data types.

    Example

    class Printer {
        // Method to print an integer
        void print(int value) {
            System.out.println("Printing integer: " + value);
        }
    
        // Overloaded method to print a double
        void print(double value) {
            System.out.println("Printing double: " + value);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Printer printer = new Printer();
            printer.print(10);       // Output: Printing integer: 10
            printer.print(10.5);     // Output: Printing double: 10.5
        }
    }
    

    Output

    Printing integer: 10
    Printing double: 10.5
    

    Explanation

    • The Printerthe class has two overloaded print() methods: one that accepts an integer and another that accepts a double.
    • The first print() method prints the integer value and the second print() method prints the double value.
    • In the Main class, an instance of Printer is created, and both print() methods are called with different argument types to demonstrate method overloading.
    • The program prints the integer and double values accordingly, showing how method overloading allows for the same method name to handle different types of input.

      Real-Life Example

      class AreaCalculator {
          // Method to calculate the area of a circle (using double)
          double area(double radius) {
              return Math.PI * radius * radius;
          }
      
          // Method to calculate the area of a rectangle (using int)
          int area(int length, int width) {
              return length * width;
          }
      }
      
      public class Main {
          public static void main(String[] args) {
              AreaCalculator areaCalc = new AreaCalculator();
              System.out.println("Area of circle: " + areaCalc.area(7.5)); // Output: Area of circle: 176.71
              System.out.println("Area of rectangle: " + areaCalc.area(5, 10)); // Output: Area of rectangle: 50
          }
      }
      

      Output

      Area of circle: 176.71458676442586
      Area of rectangle: 50
      

      Explanation

      • The AreaCalculatorthe class has two overloaded area() methods: one for calculating the area of a circle and another for calculating the area of a rectangle.
      • The first area() method accepts a double parameter for the radius of the circle and returns the calculated area using the formula πr².
      • The second area() method accepts two int parameters for the length and width of the rectangle and returns the calculated area using the formula length × width.
      • In the Main class, an instance of AreaCalculator is created, and both area() methods are called with appropriate arguments to demonstrate method overloading.
      • The program prints the area of the circle and rectangle, showing how method overloading allows for different calculations using the same method name but different parameter types.

      3. Changing the Order of Parameters

      • Method overloading can also be performed by arranging the arguments of two or more overloaded methods.
      • For example, if method 1's arguments are (String f_name, int roll_no) and the other methods are (int roll_no, String f_name), but they both have the same name, these two methods are regarded as overloaded with distinct parameter sequences.

        Example

        class Display {
            // Method to display string first, then integer
            void show(String s, int a) {
                System.out.println("String: " + s + ", Integer: " + a);
            }
        
            // Overloaded method to display integer first, then string
            void show(int a, String s) {
                System.out.println("Integer: " + a + ", String: " + s);
            }
        }
        
        public class Main {
            public static void main(String[] args) {
                Display display = new Display();
                display.show("Hello", 10);  // Output: String: Hello, Integer: 10
                display.show(20, "World");  // Output: Integer: 20, String: World
            }
        }
        

        Output

        String: Hello, Integer: 10
        Integer: 20, String: World
        

        Explanation

        • The Displaythe class has two overloaded show() methods: one that takes a String and an int as parameters, and another that takes an int and a String in reverse order.
        • The first show() method displays the string first, followed by the integer. The second show() method displays the integer first, followed by the string.
        • In the Main class, an instance of Display is created, and both show() methods are called to demonstrate method overloading based on the order of parameters.
        • The program prints the output in two different formats, showcasing how method overloading allows for flexibility in method usage with the same name but different parameter sequences.

        Real-Life Example

        class Logger {
            // Method to log a message with a string priority
            void log(String priority, int code) {
                System.out.println("Priority: " + priority + ", Code: " + code);
            }
        
            // Overloaded method to log a message with an integer priority
            void log(int code, String priority) {
                System.out.println("Code: " + code + ", Priority: " + priority);
            }
        }
        
        public class Main {
            public static void main(String[] args) {
                Logger logger = new Logger();
                logger.log("High", 101);     // Output: Priority: High, Code: 101
                logger.log(102, "Low");      // Output: Code: 102, Priority: Low
            }
        }
        

        Output

        Priority: High, Code: 101
        Code: 102, Priority: Low
        

        Explanation

        • The Loggerthe class has two overloaded log() methods: one that accepts a String priority followed by an integer code and another that accepts the parameters in reverse order.
        • The first log() method logs the priority first and then the code. The second log() method logs the code first and then the priority.
        • In the Main class, an instance of Logger is created, and both log() methods are called to demonstrate method overloading based on the order of parameters.
        • This example shows how method overloading enables the same method name to be used for different parameter sequences, providing flexibility in method invocation.

        Method Overloading Considerations

        Why is Method Overloading Not Possible by Changing the Return Type Only?

        Method overloading in Java is not possible because changing the method's return type creates ambiguity. Let's look at how uncertainty can occur.

        Example

        class Example {
            // Method 1: An integer version of the method
            int add(int a, int b) {
                return a + b;
            }
        
            // Method 2: A double version of the method
            // This will cause a compile-time error!
            double add(int a, int b) {
                return a + b + 0.0;
            }
        
            public static void main(String[] args) {
                Example obj = new Example();
                int sum1 = obj.add(10, 20); // This calls the first add method
                // double sum2 = obj.add(10, 20); // Compiler error: cannot resolve method
            }
        }
        

        Output

        // Compiler Error: Method add(int,int) is already defined in class Example
        

        Explanation

        • The Examplethe class has two methods named add(), both with the same parameter types (int and int), but one is supposed to return an int and the other a double.
        • In Java, method overloading is based on the method signature, which includes the method name and parameter types. The return type is not considered in method overloading.
        • Because both methods have the same name and parameter types, the compiler cannot distinguish between them, leading to a compile-time error.
        • To fix this, you could change the parameter types or the number of parameters to make the method signatures unique.

        When the Java Compiler Decides: Compile-Time vs Run-Time Errors

        This is why the Java compiler throws an error at compile-time if it detects method overloading with different return types. This approach safeguards your code against run-time errors, ensuring it is more robust and reliable.

        Example

        class CompileTimeExample {
            // Method 1: int version
            int multiply(int a, int b) {
                return a * b;
            }
        
            // Method 2: double version (will cause a compile-time error)
            // double multiply(int a, int b) {
            //     return a * b * 1.0;
            // }
        
            public static void main(String[] args) {
                CompileTimeExample obj = new CompileTimeExample();
                int result = obj.multiply(10, 5);  // This is fine
                // double result2 = obj.multiply(10, 5);  // Compiler will catch this error if method 2 is uncommented
            }
        }
        

        Output

        50
        // Note: If Method 2 is uncommented, a compiler error will occur:
        // Method multiply(int,int) is already defined in class CompileTimeExample
        

        Explanation

        • The CompileTimeExamplethe class contains two methods named multiply(), both with the same parameters (int a and int b), but with different return types (int for one, double for the other).
        • In Java, method overloading depends on the method signature, which includes the method name and the parameter types. The return type is not part of the method signature for overloading.
        • Uncommenting the second method would cause a compile-time error because the compiler cannot differentiate between the two methods based on their parameter list alone.
        • The correct way to overload the method would be to change the parameter list, for example, by changing the parameter types or adding an additional parameter.

        Can We Overload Static Methods?

        Yes, static methods can be overloaded. The example below provides a static method called pet that has been overloaded with various kinds and parameters.

        Example

        class StaticMethodExample {
            // Static method with one parameter
            static void display(int a) {
                System.out.println("Integer: " + a);
            }
        
            // Overloaded static method with two parameters
            static void display(int a, int b) {
                System.out.println("Sum: " + (a + b));
            }
        
            // Overloaded static method with different parameter types
            static void display(String a) {
                System.out.println("String: " + a);
            }
        
            public static void main(String[] args) {
                // Calling the overloaded static methods
                StaticMethodExample.display(10);         // Calls the first method
                StaticMethodExample.display(10, 20);     // Calls the second method
                StaticMethodExample.display("Hello");    // Calls the third method
            }
        }
        

        Output

        Integer: 10
        Sum: 30
        String: Hello
        

        Explanation

        • The StaticMethodExamplethe class demonstrates method overloading with static methods. The display method is overloaded three times with different parameter lists: one with a single integer, one with two integers, and one with a string.
        • The first method is called with a single integer, which prints the integer value. The second method is called with two integers, which adds the integers and prints their sum. The third method is called with a string, which prints the string value.
        • Overloading static methods follows the same rules as overloading instance methods, allowing multiple methods with the same name but different parameter lists within the same class.

        Can We Overload the main() Method?

        Yes, the main() method can be overloaded. The following example demonstrates a simple implementation of overloading the main() function with a distinct set of parameters.

        Example

        class MainMethodOverload {
            // Standard main method called by JVM
            public static void main(String[] args) {
                System.out.println("Standard main method");
                
                // Calling overloaded main methods explicitly
                main(10);
                main("Hello");
            }
        
            // Overloaded main method with an integer parameter
            public static void main(int a) {
                System.out.println("Overloaded main method with int: " + a);
            }
        
            // Overloaded main method with a String parameter
            public static void main(String a) {
                System.out.println("Overloaded main method with String: " + a);
            }
        }
        

        Output

        Standard main method
        Overloaded main method with int: 10
        Overloaded main method with String: Hello
        

        Explanation

        • The MainMethodOverloadthe class demonstrates method overloading with the main method. Although the mainthe method is typically used as the entry point for a Java application; it can be overloaded with different parameter lists.
        • The standard main(String[] args)The JVM calls the method to start the application. Within this method, two overloaded versions of the main method is explicitly called one with an integer parameter and one with a string parameter.
        • The overloaded main(int a) and main(String a) methods are invoked from the standard main method, demonstrating that you can define multiple main methods with different parameter types. However, only the standard main method is used to start the Java application.

        What if the exact prototype does not match the arguments?

        What if the exact prototype does not match the arguments?
        Priority-wise, the compiler takes the following steps:
        • Type conversion to a higher type (in terms of range) within the same family.
        • Type conversion to a subsequent higher family (for example, if no long data type is available for an int data type, it will look for a float data type).

        Example

        class TypeConversionExample {
            // Method with an int parameter
            void show(int a) {
                System.out.println("int: " + a);
            }
        
            // Method with a double parameter
            void show(double a) {
                System.out.println("double: " + a);
            }
        
            // Method with a String parameter
            void show(String a) {
                System.out.println("String: " + a);
            }
        
            public static void main(String[] args) {
                TypeConversionExample obj = new TypeConversionExample();
        
                obj.show(10);       // Exact match with int
                obj.show(10L);      // No long method, so int method is used (widening to int)
                obj.show(10.5f);    // float is widened to double
                obj.show("Hello");  // Exact match with String
            }
        }
        

        Output

        int: 10
        double: 10.0
        double: 10.5
        String: Hello
        

        Explanation

        • The TypeConversionExample class demonstrates method overloading with different parameter types: int, double, and String.
        • In the main method:
        • obj.show(10); directly matches the show(int a) method.
        • obj.show(10L); is a long value. Since there's no exact long method, Java performs widening conversion to int and calls show(int a).
        • obj.show(10.5f); is a float value. Java widens it to double and calls.show(double a).
        • obj.show("Hello"); Matches the show(String a) method exactly.
        • Method overloading resolves to the most specific method available based on the parameter types and conversions.
        Summary
        Method overloading in Java allows for several methods with the same name but different parameters, which improves code readability and flexibility. It is implemented via modifying parameter numbers, types, or order instead of just changing the return type. Overloading also applies to static methods and the main() function, allowing the same method name to be used in several circumstances. Master Method Overloading and other Java concepts with ScholarHat's Full-Stack Java Developer Certification Training Course.

          FAQs

          Q1. What is the purpose of method overloading in Java?

          The goal of method overloading in Java is to allow a class to have many methods with the same name but distinct parameters, allowing the same method name to do different functions depending on input. This makes code more readable, reusable, and flexible.

          Q2. Which methods Cannot be overloaded in Java?

          Overloading methods that differ simply by their return type is not possible in Java. Additionally, methods with the same name and parameter types in the same class cannot be overloaded, even if their return types differ.

          Q3. Can we have different return types in method overloading?

          Yes, method overloading allows for distinct return types, but the methods must also have different parameter lists. Overloading based purely on the return type is not permitted in Java since it causes uncertainty during method calls.

          Q4. Can method overloading be used with constructors in Java?

          Yes, method overloading can be utilized with Java constructors. Constructors can be overloaded by creating numerous constructors in a class with distinct argument lists. This allows for several methods of initializing the class's objects.

          Q5. Does method overloading apply to inherited methods in Java?

          Yes, method overloading extends to inherited methods as well. Subclasses can overload methods inherited from a superclass by creating methods with the same name but different parameters. This enables subclasses to develop customized implementations depending on their own requirements.

          Q6. Can overloaded methods be overridden in Java?

          Overloaded methods are not overwritten, but they can be. Overloading occurs when many methods with the same name but different parameters are defined within the same class. Overriding happens when a subclass provides a specialized implementation of a method already defined in its superclass, using the same name and parameters.
          Share Article

          Live Classes Schedule

          Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
          Angular Certification TrainingOct 13SAT, SUN
          Filling Fast
          08:30PM to 10:30PM (IST)
          Get Details
          Full-Stack .NET Developer Certification TrainingOct 13SAT, SUN
          Filling Fast
          07:00AM to 09:00AM (IST)
          Get Details
          ASP.NET Core ProjectOct 19SAT, SUN
          Filling Fast
          10:00AM to 12:00PM (IST)
          Get Details
          Advanced Full-Stack .NET Developer Certification TrainingOct 20SAT, SUN
          Filling Fast
          09:30AM to 11:30AM (IST)
          Get Details
          .NET Solution Architect Certification TrainingOct 20SAT, SUN
          Filling Fast
          05:30PM to 07:30PM (IST)
          Get Details
          .NET Microservices Certification TrainingOct 20SAT, SUN
          Filling Fast
          05:30PM to 07:30PM (IST)
          Get Details
          ASP.NET Core Certification TrainingOct 20SAT, SUN
          Filling Fast
          09:30AM to 11:30AM (IST)
          Get Details
          Microsoft Azure Cloud Architect with AINov 10SAT, SUN
          Filling Fast
          07:00AM to 09:00AM (IST)
          Get Details

          Can't find convenient schedule? Let us know

          About Author
          Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

          Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
          Accept cookies & close this