Method Overloading with Different Parameter Types and Their Subclasses in Java


Write a Java program to demonstrate method overloading with different parameter types and their subclasses

  • In the main method, an instance of the MethodOverloadingDemo class is created.
  • Various printInfo methods of MethodOverloadingDemo are called with different arguments.
  • The printInfo method is overloaded to accept both String and Number arguments.
  • When printer.printInfo(str) is called, it matches the method with a String parameter.
  • When printer.printInfo(integer) is called, it matches the method with a Number parameter because Integer is a subclass of Number.
  • Similarly, when printer.printInfo(dbl) is called, it also matches the method with a Number parameter because Double is also a subclass of Number.
  • The appropriate overloaded methods are called based on the arguments passed, and the corresponding messages are printed to the console.

Source Code

public class OverloadingWithSubclassesDemo
{
	public static void main(String[] args)
	{
		MethodOverloadingDemo printer = new MethodOverloadingDemo();
 
		String str = "Hello World!";
		Integer integer = 23;
		Double dbl = 84.14;
 
		printer.printInfo(str);      // Calls the method for String
		printer.printInfo(integer);  // Calls the method for Number
		printer.printInfo(dbl);      // Calls the method for Number (Double is a subclass of Number)
	}
}
class MethodOverloadingDemo
{
	void printInfo(String message)
	{
		System.out.println("Printing String : " + message);
	}
 
	void printInfo(Number number)
	{
		System.out.println("Printing Number : " + number);
	}
}

Output

Printing String : Hello World!
Printing Number : 23
Printing Number : 84.14

Example Programs