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:
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 } } }
Superclass: Hello, from the Superclass Superclass: Hello, from the Subclass Subclass: Hello, with overloading (with new parameter)
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions