Method Overloading

Defining more than one method with same name but with unique set of method arguments is called as Method Overloading.

package com.techstackjournal.methodoverloading;

public class MethodOverloadingExample {

	public static double sumArray(double[] nums) {
		double sum = 0;

		System.out.println("Inside sumArray(double[] nums)");

		for (int i = 0; i < nums.length; i++) {
			sum += nums[i];
		}

		return sum;
	}

	protected static int sumArray(int[] nums) {
		int sum = 0;

		System.out.println("Inside sumArray(int[] nums)");

		for (int i = 0; i < nums.length; i++) {
			sum += nums[i];
		}

		return sum;
	}

	public static double sumArray(double[] nums, int fromIndex) {
		double sum = 0;

		System.out.println("Inside sumArray(double[] nums, int fromIndex)");

		for (int i = fromIndex; i < nums.length; i++) {
			sum += nums[i];
		}

		return sum;
	}

	public static double sumArray(double[] nums, int fromIndex, int endIndex) {
		double sum = 0;

		System.out.println("Inside sumArray(double[] nums, int fromIndex, int endIndex)");

		for (int i = fromIndex; i < nums.length && i <= endIndex; i++) {
			sum += nums[i];
		}

		return sum;
	}

}

In the above example, we have 4 methods with same name but the arguments are unique for each method.

package com.techstackjournal.methodoverloading;

public class Application {

	public static void main(String[] args) {

		int[] nums1 = { 1, 2, 3 };
		double[] nums2 = { 10, 20, 30, 40, 50, 60 };

		System.out.println(MethodOverloadingExample.sumArray(nums1));
		System.out.println(MethodOverloadingExample.sumArray(nums2));
		System.out.println(MethodOverloadingExample.sumArray(nums2, 3));
		System.out.println(MethodOverloadingExample.sumArray(nums2, 2, 4));

	}

}
Inside sumArray(int[] nums)
6
Inside sumArray(double[] nums)
210.0
Inside sumArray(double[] nums, int fromIndex)
150.0
Inside sumArray(double[] nums, int fromIndex, int endIndex)
120.0

Method Overloading Rules:

  • Arguments of all methods must be unique
  • Two methods with same set of arguments but with different return type is not legal, compiler will throw an error while compiling
  • You may have same return type or different return type
  • You may have different access modifiers for overloaded methods
  • Method overloading works for both static and non-static methods