Method Overloading with Overloaded Methods That Use Different Parameter Types, Including Booleans and Integers in Java


Create a Java program to demonstrate method overloading with overloaded methods that use different parameter types, including booleans and integers

  • The NumberChecker class contains two overloaded isPositive methods.
  • The first isPositive method takes an int argument and returns true if the number is positive, otherwise false.
  • The second isPositive method takes a boolean argument and simply returns the same boolean value.
  • In the Main class, an instance of NumberChecker named checker is created.
  • The isPositive method is called twice with different arguments: once with an int value 5 and once with a boolean value true.
  • For the first call, the int version of isPositive is invoked, which returns true because 5 is positive.
  • For the second call, the boolean version of isPositive is invoked, which returns true because it simply returns the same boolean value that was passed to it (true in this case).

Source Code

class NumberChecker
{
	boolean isPositive(int number)
	{
		return number > 0;
	}
 
	boolean isPositive(boolean flag)
	{
		return flag;
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		NumberChecker checker = new NumberChecker();
		System.out.println("Is 5 Positive ? " + checker.isPositive(5));
		System.out.println("Is 'true' Positive ? " + checker.isPositive(true));
	}
}

Output

Is 5 Positive ? true
Is 'true' Positive ? true

Example Programs