In this Java program, you are demonstrating method overriding and the use of exception handling. The program defines a Parent class and a Child class that inherits from Parent. The Child class overrides the display method and changes the exception type it can throw. Here's an explanation of the program:
In this program, the display method in the Child class overrides the one in the Parent class, and it changes the type of exception it can throw. This is allowed because a subclass method can throw a subtype of the exception thrown by the parent method.
When you call the display method on the parent object, it actually invokes the display method of the Child class, and "Child's display method" is printed to the console. However, the display method in the Child class throws a RuntimeException, which is not explicitly caught in the main method. Therefore, an unhandled exception occurs, and the stack trace is printed to the console.
The throws clause in the method declaration indicates the types of exceptions that a method can throw. Subclasses can throw exceptions that are subclasses of the exceptions thrown by the parent class method, but they cannot throw broader exceptions.
public class MethodOverride // Main class { public static void main(String[] args) { Parent parent = new Child(); try { parent.display(); } catch (Exception e) { e.printStackTrace(); } } } class Parent // Parent class { void display() throws Exception { System.out.println("Parent's display method"); } } class Child extends Parent // Child class { @Override void display() throws RuntimeException { System.out.println("Child's display method"); } }
Child's display method
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions