Write a Java program to demonstrate method overriding with a subclass that overrides a method from a superclass and uses the same method name, parameter list, and return type while adding a checked exception
The code define Parent class with a calculate method that throws an Exception, and a Child class that extends Parent and overrides the calculate method to throw an InterruptedException. Here's an explanation of the code:
It's important to note that the overridden method in the Child class can throw a more specific exception (InterruptedException) than the exception declared in the superclass (Exception). This is allowed in Java because it's considered more specific and follows the principle of covariant exception overriding. The InterruptedException is a subclass of Exception.
class Parent { int calculate(int x, int y) throws Exception { System.out.println("Parent class calculation"); return 0; } } class Child extends Parent { int calculate(int a, int b) throws InterruptedException { System.out.println("Child class calculation"); Thread.sleep(1000); return a + b; } } public class Main { public static void main(String[] args) throws Exception { Child child = new Child(); System.out.println("Sum : " + child.calculate(4, 7)); } }
Child class calculation Sum : 11
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions