How to Call Overloaded Methods with NULL as Argument in Java (To Resolve Ambiguous Methods Error)

Java, being an object oriented programming language supports overloading of methods. This feature enables you to write any number of methods with the same name, but with different types of arguments. What would you do when you need to pass null as the arguments? Lets see an example. 

public class Overload 
{
	public static void main(String args[])
	{
		Integer dvalue = findSum(null,null);
	}
		
	public static Integer findSum(Integer value1, Integer value2)
	{
		return value1 + value2;
	}
		
	public static Integer findSum(Double value1, Double value2)
	{
		return (int)(value1 + value2);
	}
}

In the above example, the compiler will complain that "The method findSum(Integer, Integer) is ambiguous for the type Overload". To correctly call the method you intended, you should typecast "null" into appropriate type as shown in the corrected code below.

public class Overload 
{
	public static void main(String args[])
	{
		Integer sum1 = findSum((Integer)null, (Integer)null);

		Integer sum2 = findSum((Double)null, (Double)null);
	}
		
	public static Integer findSum(Integer value1, Integer value2)
	{
		return value1 + value2;
	}
		
	public static Integer findSum(Double value1, Double value2)
	{
		return (int)(value1 + value2);
	}
}

In 99% of the cases, this issue happens because of improper design of the program.

Powered by Bullraider.com