Method Overloading with Different Data Types and a Common Parameter in Java


Write a Java program to demonstrate method overloading with two methods having different data types and a common parameter

The Java code defines a class named Printer, which encapsulates methods for printing different types of data. Within this class, there are two methods named print, each catering to different types of input parameters. This technique is known as method overloading, which allows multiple methods with the same name but different parameter lists to coexist within a class. The first print method accepts a single parameter of type String, indicating it is intended for printing strings. Inside this method, the input string is concatenated with the prefix "String : " and then printed to the console using System.out.println().

Similarly, the second print method takes a single parameter of type int, signifying its purpose to print integers. Within this method, the integer parameter is concatenated with the prefix "Integer : ", forming the appropriate message, which is then displayed using System.out.println(). By providing method overloads for different data types, the Printer class offers flexibility and convenience in printing various types of data without the need for separate method names.

In the main method, an instance of the Printer class named Printer is created using the new keyword. This instantiation allocates memory for the Printer object, enabling access to its methods. Subsequently, two method calls are made on the Printer object. Firstly, the print method is invoked with a String parameter "Hello World", resulting in the string being printed with the prefix "String : ". Secondly, the print method is called with an int parameter 47, causing the integer to be printed with the prefix "Integer : ". This demonstrates the utility of method overloading, allowing the Printer class to handle diverse data types seamlessly within a unified interface.

Source Code

class Printer
{
	void print(String text)
	{
		System.out.println("String : " + text);
	}
 
	void print(int num)
	{
		System.out.println("Integer : " + num);
	}
 
	public static void main(String[] args)
	{
		Printer Printer = new Printer();
		Printer.print("Hello World");
		Printer.print(47);
	}
}

Output

String : Hello World
Integer : 470

Example Programs