Method Overloading with Different Parameter Types and Varargs in Java


Create a Java program to demonstrate method overloading with different parameter types and varargs

This Java program demonstrates method overloading in a class named ShoppingList, which allows adding items to a shopping list with or without specifying quantities. Let's break down the code:

  • The main method creates an instance of the ShoppingList class.
  • It then calls the addItems methods with different arguments.
  • The Java compiler determines which overloaded method to call based on the number and type of arguments passed.
  • For the first call, list.addItems("Milk", "Bread", "Eggs"), the addItems(String... items) method is invoked, adding items to the shopping list without specifying quantities.
  • For the second call, list.addItems(5, "Apples", "Bananas"), the addItems(int quantity, String... items) method is invoked, adding items to the shopping list with specified quantities.
  • The items are then printed to the console accordingly.

Source Code

class ShoppingList
{
	void addItems(String... items)
	{
		System.out.println("Adding items to the shopping list :");
		for (String item : items)
		{
			System.out.println("- " + item);
		}
	}
 
	void addItems(int quantity, String... items)
	{
		System.out.println("Adding items with quantities to the shopping list :");
		for (String item : items)
		{
			System.out.println("- " + quantity + " " + item);
		}
	}
 
	public static void main(String[] args)
	{
		ShoppingList list = new ShoppingList();
		list.addItems("Milk", "Bread", "Eggs");
		list.addItems(5, "Apples", "Bananas");
	}
}

Output

Adding items to the shopping list :
- Milk
- Bread
- Eggs
Adding items with quantities to the shopping list :
- 5 Apples
- 5 Bananas

Example Programs