Method Overloading with Different Parameter Types and Generic Methods in Java


Write a Java program to demonstrate method overloading with different parameter types and generic methods

This Java program demonstrates method overloading with generics. It defines a class MethodOverloadingDemo with overloaded add methods for adding integers, concatenating strings, and a generic method to add two values of any type. Another class OverloadingWithGenericsDemo is used to demonstrate these overloaded methods.

  • In the MethodOverloadingDemo class, there are three overloaded add methods:
    • One to add two integers.
    • One to concatenate two strings.
    • One generic method to add two values of any type. In this case, it simply returns the first parameter.
  • In the OverloadingWithGenericsDemo class, an instance of MethodOverloadingDemo is created.
  • Various add methods are invoked with different arguments.
  • The appropriate overloaded method is called based on the argument types provided.
  • For the generic add method, it returns the first parameter, which is a double in this case.
  • The results are then printed to the console.

Source Code

public class OverloadingWithGenericsDemo
{
	public static void main(String[] args)
	{
		MethodOverloadingDemo calculator = new MethodOverloadingDemo();
 
		int sumInt = calculator.add(10, 20);
		String concatStr = calculator.add("Hello ", "World");
		Object result = calculator.add(3.7, 10.5); // Using generic method
 
		System.out.println("Sum of Integers : " + sumInt);
		System.out.println("Concatenation of Strings : " + concatStr);
		System.out.println("Generic Result : " + result);
	}
}
class MethodOverloadingDemo
{    
	int add(int a, int b)// Method to add two integers
	{
		return a + b;
	}
 
	String add(String a, String b)// Method to concatenate two strings
	{
		return a + b;
	}
 
	<T> T add(T a, T b) // Generic method to add two values of any type
	{
		return a;
	}
}

Output

Sum of Integers : 30
Concatenation of Strings : Hello World
Generic Result : 3.7

Example Programs