Subclass Method Adds New Parameter with Default Value In Java


Create a Java program to demonstrate method overriding with a subclass that overrides a method and adds a new parameter with a default value

The code defines MethodOverloadingDemo class with a main method and two classes, Superclass and Subclass. The Superclass has a method printMessage(String message), and the Subclass overloads this method with an additional parameter boolean withNewParameter. Here's an explanation of the code:

  • In the MethodOverloadingDemo class's main method, you create instances of Superclass and Subclass named superObj and subObj, respectively.
  • You then call the printMessage method on both superObj and subObj.
  • The Superclass's printMessage method simply prints a message with "Superclass: " prefix.
  • The Subclass's printMessage method overloads the method. If the withNewParameter parameter is true, it prints the message with "(with new parameter)" added to it. If withNewParameter is false, it calls the superclass's printMessage method, effectively delegating to the parent class's method.

Source Code

public class MethodOverloadingDemo
{
    public static void main(String[] args)
	{
        Superclass superObj = new Superclass();
        Subclass subObj = new Subclass();
 
        superObj.printMessage("Hello, from the Superclass");
        subObj.printMessage("Hello, from the Subclass");
        subObj.printMessage("Hello, with overloading", true);
    }
}
class Superclass
{
    void printMessage(String message)
	{
        System.out.println("Superclass: " + message);
    }
}
 
class Subclass extends Superclass
{
			// This method overloads the printMessage method
    void printMessage(String message, boolean withNewParameter)
	{
        if (withNewParameter)
		{
            System.out.println("Subclass: " + message + " (with new parameter)");
        }
		else
		{
            printMessage(message); // Call the superclass method
        }
    }
}

Output

Superclass: Hello, from the Superclass
Superclass: Hello, from the Subclass
Subclass: Hello, with overloading (with new parameter)