Java Reference
In-Depth Information
Why Does This Rule Exist When
Overriding a Method? (continued)
Notice that it has a connect() method that does not declare any exceptions. The following
Child class extends Parent and overrides the connect() method:
public class Child extends Parent
{
public void connect() throws java.io.IOException
{
System.out.println(“Inside connect() in Child”);
throw new java.io.IOException();
}
}
The Child class does not compile because its connect() method declares an IOExcep-
tion, and the overridden connect() method in Parent does not declare any exceptions.
Let's assume, however, that this rule involving exceptions and overriding methods did
not exist and that the Child class compiled successfully. Then, through polymorphism, the
following statement is valid:
Parent p = new Child();
The reference p is of type Parent, but the object is of type Child. This is valid because a
Child object is a Parent object. Now, consider the following program, which invokes the
connect() method using this reference p:
public class Test
{
public static void main(String [] args)
{
Parent p = new Child();
p.connect();
}
}
This program compiles because the Parent class has a connect() method. However,
because of virtual method invocation, which method executes at run time? Not the one in
Parent, but the overridden method in Child. The connect() method in Child throws an IOEx-
ception, but who catches it? Nobody. And we just created a situation in which a checked
exception went unchecked. The compiler thought I was invoking connect() in Parent, which
did not declare any exceptions. However, at run time, the connect() method in Child is
what executes, and that method throws an IOException.
The compiler cannot predict the Handle or Declare Rule in this situation. This is why
child class methods that override parent class methods cannot throw “more” exceptions
than the parent class method; if they could, a checked exception could occur that might
never be caught.
Search WWH ::




Custom Search