Subclass Method Adds Checked Exception to Superclass Method In Java


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:

  • Parent is a class with a method calculate(int x, int y) that throws an Exception. This method prints "Parent class calculation" to the console and returns 0.
  • Child is a subclass of Parent. It overrides the calculate method by providing its own implementation. In the Child class, the calculate method takes different parameters (int a, int b) and throws an InterruptedException. This method prints "Child class calculation" to the console, sleeps the current thread for one second, and returns the sum of a and b.
  • In the Main class's main method, you create an instance of the Child class named child.
  • You call the calculate method on the child object, passing arguments 4 and 7. This method returns the sum of the arguments and waits for one second.
  • The result is printed to the console as "Sum : 11" (4 + 7).

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.

Source Code

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));
    }
}

Output

Child class calculation
Sum : 11