Method Overloading with Overloaded Methods That Use Different Parameter Types and Return Types Including Type Casting in Java


Create a Java program to demonstrate method overloading with overloaded methods that use different parameter types and return types, including type casting

  • The Calculator class contains two add methods: one that accepts two integers and another that accepts two doubles.
  • The first add method adds two integers and returns the result.
  • The second add method adds two doubles and returns the result. It explicitly casts the result to a double to ensure that the result is of type double.
  • In the Main class, an instance of the Calculator class is created.
  • The add method is called twice, once with integers and once with doubles.
  • In each case, the appropriate add method is invoked based on the argument types, and the result is printed.

Source Code

class Calculator
{
	int add(int a, int b)
	{
		return a + b;
	}
 
	double add(double a, double b)
	{
		return (double) (a + b);
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Calculator calculator = new Calculator();
		System.out.println("Sum of Two Integers : " + calculator.add(5, 3));
		System.out.println("Sum of Two Doubles (with Casting) : " + calculator.add(3.5, 2.7));
	}
}

Output

Sum of Two Integers : 8
Sum of Two Doubles (with Casting) : 6.2

Example Programs