Subclass Method Overrides Superclass Method and Throws Subclass Exception In Java


Create a Java program to demonstrate method overriding with a subclass that overrides a method and throws a subclass exception

Class hierarchy with a Parent class and a Child class that extends Parent. Both classes have a display method, but in the Child class, you've overridden the display method. The display method in the Parent class declares that it can throw an Exception, and the overridden display method in the Child class declares that it can throw a RuntimeException. Here's what happens when you run the main method:

  • You create a Parent reference variable parent and assign it an instance of the Child class. This is allowed because a subclass object can be assigned to a superclass reference variable.
  • You call the display method on the parent reference, which invokes the overridden display method in the Child class.
  • The Child class's display method throws a RuntimeException, specifically a RuntimeException subclass.
  • In the main method, you have a try-catch block to catch Exception, so it catches the exception thrown by the display method. However, since RuntimeException is not a subclass of Exception (in fact, it's a subclass of java.lang.Exception), the catch block will not catch this exception.

Source Code

class Parent
{
    void display() throws Exception
	{
        System.out.println("Parent's display method");
    }
}
 
class Child extends Parent
{
    @Override
    void display() throws RuntimeException
	{
        System.out.println("Child's display method");
    }
}
 
public class Main
{
    public static void main(String[] args)
	{
        Parent parent = new Child();
        try{
            parent.display();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output

Child's display method