Method overloading is a very important feature in Java. It helps you use the same method name for the same functionality. In this article, we will be exploring method overloading.

  1. How Method Overloading Works
  2. Different Ways to overload a method
  3. Return Types in Method Overloading
  4. Constructor Overloading
  5. Benefits of Method Overloading
  6. Method Overloading and Polymorphism

Method Overloading in Java

How Method Overloading Works

Method overloading allows having more than one method in a class with the same name but with different type/number of arguments.  When an overloaded method is invoked, the type/number of arguments in the method call is matched with each version of the overloaded method, and the one that matches is invoked.

Different Ways to overload a method

As mentioned earlier, methods can be overloaded based on the type of parameters, a number of parameters, or both. Let us understand each of these methods in detail.

Based on Number of Parameters

Methods can be overloaded based on the number of parameters. So, you can have two or more methods in a class with the same name but with a different number of parameters.

Sample Code


public class Greeting {

    public void sayHello() {
        System.out.println("Hello World");
    }

    public void sayHello(String firstName) {
        System.out.println("Hello "+firstName);
    }

    public void sayHello(String firstName,String lastName) {
        System.out.println("Hello "+firstName+" "+lastName);
    }

    public static void main(String args[]) {
        Greeting greeting = new Greeting();
        greeting.sayHello();
        greeting.sayHello("John");
        greeting.sayHello("John Doe");
    }

}

  • This code specifies a Greeting class
  • Line 3 specifies a sayHello method. It does not accept any arguments and simply prints Hello World to the console
  • Line 7 also specifies a sayHello method. It accepts a single String argument which is the firstName of a person and prints a greeting with this value
  • Line 11 specifies another sayHello method. This accepts two arguments firstName and lastName. It prints a greeting with both these values.
  • So, the sayHello method is overloaded three times, each accepts a different number of arguments.
  • Line 15 specifies a main method
  • Line 17 invokes the sayHello method without any arguments. Since no arguments are passed, this is matched to the sayHello method at Line 3 and this method is invoked.
  • Line 18 invokes the sayHello method with a single String argument. This is similarly matched to the sayHello method at Line 7
  • Line 19 invokes the sayHello method with two String arguments. Again, this is matched to the sayHello method at Line 11
  • So, depending on the number of parameters passed to the sayHello method, the correct version of the method is invoked.

Output

Hello World
Hello John
Hello John Doe

Based on Type of Parameters

Methods can also be overloaded based on the type of parameters. So, you can have two or more methods in a class with the same name but with different types of parameters.

Sample Code


public class Calculator {

    public int doubleInput(int a) {
        return a * 2;
    }

    public double doubleInput(double a) {
        return a * 2;
    }

    public static void main(String args[]) {
        Calculator calculator = new Calculator();
        int result1 = calculator.doubleInput(10);
        System.out.println("Result 1:"+result1);
        double result2 = calculator.doubleInput(20.5);
        System.out.println("Result 2:"+result2);
    }

}

  • The code specifies a Calculator class.
  • It has a doubleInput method that is overloaded two times. The method at Line 3 accepts an int argument while the method at Line 7 accepts a double argument.
  • Both methods multiply the input by 2 and return the result.
  • Line 13 invokes the doubleInput method with an int value which is matched to the doubleInput method at Line 3
  • Similarly, Line 15 invokes the doubleInput method with a double value which is matched to the doubleInput method at Line 7
  • So, depending on the type of parameters passed to the doubleInput method, the correct version of the method is invoked.

Output

Result 1:20
Result 2:41.0

Return Types in Method Overloading

It is important to note that method overloading can occur only on the basis of arguments. You cannot overload a method based on its return type. So, if you specify multiple methods with the same number/type of arguments but with different return types, a compilation error will occur.

Sample Code

public class RandomNumberGenerator {

    public int getRandom() {
        Random random = new Random();
        int num = random.nextInt();
        return num;
    }

    public double getRandom() {
        Random random = new Random();
        double num = random.nextDouble();
        return num;
    }

}
  • The code specifies a RandomNumberGenerator class
  • Line 3 specifies a getRandom method that returns a random int value
  • Line 9 specifies a getRandom method that returns a random double value.
  • Since both methods have the same name and both do not accept any arguments, this will cause a compilation error although both methods have a different return type

Constructor Overloading

Just like methods, constructors can also be overloaded based on the type/number of arguments.

Sample Code

public class Person {
	
	private String name;
	private int age;
	
	public Person() {
		name = “John”;
		age = 18;
	}
	
	public Person(String name,int age) {
		this.name = name;
		this.age = age;
	}
	
	public Person(String name) {
		this.name = name;
		this.age = 18;
	}

}
  • This code defines a Person class with name and age fields
  • Line 6 specifies a constructor that does not accept any arguments, it initializes name and age to some default values
  • Line 11 specifies a constructor that accepts arguments corresponding to name and age and initializes the fields to these values
  • Line 16 specifies a constructor that accepts an argument corresponding to the name. It initializes the name field with the value passed in and the age field with a default value.
  • So, the Person class constructor is overloaded three times.

Benefits of method overloading

The main advantage of method overloading is that you can use the same method name for methods that perform the same functionality but only vary in the arguments. Without method overloading, methods that perform the same functionality need to be named differently. This is not a very good approach as it makes the code difficult to read and confusing for developers who use the code.

So, for example, earlier we had created a Greeting class that had an overloaded method called sayHello. Without overloading, this class would need to have methods like sayHello(), sayHelloWithFirstName(), sayHelloWithFirstNameAndLastName().

So, although all three methods do the same thing, they need to be named differently. This clutters the code and makes it confusing.

Method Overloading and polymorphism

Method overloading is one of the ways in which Java achieves polymorphism. Polymorphism simply refers to the ability to perform an operation in different ways. Since method overloading allows the same method name to be used to execute different functionality based on the number/type of arguments, it is an example of polymorphism. Method overloading is an example of compile-time polymorphism. This is because the version of an overloaded method that will be invoked is known at compile time. Java also supports runtime polymorphism through method overriding.

Conclusion

So, just to summarize, method overloading allows having more than one method with the same name in a class. The methods need to differ on the type/number of arguments. Methods cannot be overloaded based on their return types. Just like methods, constructors can also be overloaded. Method overloading helps to keep the code clean by having methods that perform the same functionality have the same name. Method overloading helps to achieve compile-time polymorphism.