Program to show - overridden method of subclass can declare/throw narrower (subclass of) checked exception

If superclass method throws/declare checked/compileTime exception - overridden method of subclass can declare/throw narrower (subclass of) checked exception

IOException is superclass of FileNotFoundException.

import java.io.FileNotFoundException;
import java.io.IOException;
class SuperClass{
   void method() throws IOException{
          System.out.println("superClass method");
   }
}
class SubClass extends SuperClass{
   void method() throws FileNotFoundException{
          System.out.println("SubClass method");
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class ExceptionTest {
   public static void main(String[] args) throws Exception {
          SuperClass obj=new SubClass();
          obj.method();
   }
}
/*OUTPUT
SubClass method
*/

No comments:

Post a Comment