Alex Rivera | Logout

Inheritance , method signature , method overriding and throws clause

Asked 2012-01-27T15:47:29.563
20

My Parent class is :

import java.io.IOException;
public class Parent {
        int x = 0;
        public int getX() throws IOException{
        if(x<=0){
         throw new IOException();
        }
       return x;
      }
 }

I extend this class to write a subclass Child:

public class Child1 extends Parent{
     public int getX(){
        return x+10;
   }
}

Notice while overriding the getX method in the Child class , I have removed the throws clause from the method definition .Now it results in an anomalous behavior by the compiler which is expected :

new Parent().getX() ;

does not compile without enclosing it in a try-catch block , as expected .

new Child().getX() ;

compiles without enclosing it in a try-catch block .

But the below lines of code needs the try-catch block .

Parent p = new Child();
p.getX();

As this could be foreseen i.e. using a parent class reference to invoke a child method during run-time polymorphism , why the designers of Java didn't make it mandatory to include the throws clause in the method definition while overriding a particular parent class method ? I mean if a parent class method has throws clause in its definition , then while overriding it the overriding method should also include the throws clause , Ain't it ?

Edit
Report

1 Answer

5

Well, the overriding method might not throw any exception at all (or at least fewer exceptions), thus you can remove exceptions from the throw clause (or the throw clause as a whole).

Suppose the overriding method catches all exceptions, logs them and returns a special value. Although that's not good style (it would change the semantics of the method) it is still possible andd thus you'd not have to catch exceptions that are never thrown if you know at compile time that you're dealing with a Child.

Adding exceptions won't work, since users of the class who access it through the Parent reference don't know of any exceptions that Child might add.

answered 2012-01-27T15:51:07.453

Your Answer