OCA Java SE 8 Mock Exam - OCA Mock Question 24








Question

What is the output of the following code?

         class MainBase { 
             void myMethod() throws ExceptionInInitializerError { 
                 System.out.println("Base"); 
             } 
          } 
         class MainDerived extends MainBase { 
             void myMethod() throws RuntimeException { 
                 System.out.println("Derived"); 
             } 
          } 
         public class Main { 
             public static void main(String args[]) { 
                 MainBase obj = new MainDerived(); 
                 obj.myMethod(); 
             } 
          } 

    a  Base 

    b  Derived 

    c  Derived 
       Base 

    d  Base 
       Derived 

    e  Compilation error 





Answer



B

Note

If a base class method doesn't throw an exception, an overriding method in the derived class can't throw a exception applies only to checked exceptions.

It doesn't apply to runtime (unchecked) exceptions or errors.

A base or overridden method is free to throw any Error or runtime exception.

         class MainBase { 
             void myMethod() throws ExceptionInInitializerError { 
                 System.out.println("Base"); 
             } //  ww  w  . j  av a  2s .co m
          } 
         class MainDerived extends MainBase { 
             void myMethod() throws RuntimeException { 
                 System.out.println("Derived"); 
             } 
          } 
         public class Main { 
             public static void main(String args[]) { 
                 MainBase obj = new MainDerived(); 
                 obj.myMethod(); 
             } 
          } 

The code above generates the following result.