Java OCA OCP Practice Question 793

Question

How many lines of the following application do not compile?

package mypkg; /*from  w w w.j  a v  a  2  s.  co  m*/
class Exception1 extends Exception {} 
class Pet { 
   Pet getPet() throws Exception1 { 
      throw new RuntimeException("fish!"); 
   } 
} 
public final class Main extends Pet { 
   public final Main getPet() { 
      throw new RuntimeException("clown!"); 
   } 
   public static void main(String[] bubbles) { 
      final Pet f = new Main(); 
      f.getPet(); 
      System.out.println("swim!"); 
   } 
} 
  • A. None. The code compiles and prints swim!.
  • B. None. The code compiles and prints a stack trace.
  • C. One
  • D. Two
  • E. Three


C.

Note

The code does not compile, so Options A and B are incorrect.

The getPet() method is declared properly in the Pet class and successfully overridden in the Main class.

An overridden method must not declare any new or broader checked exceptions, but it is allowed to declare narrower exceptions or drop checked exceptions.

The overridden method also uses a covariant return type.

The use of final on the method and class declarations has no meaningful impact, since the methods and classes are not extended in this application.

So where does the compilation error occur?

In the main() Even though the Main version of getPet() does not declare a checked exception, the call f.getPet() uses a Pet reference variable.

Since the Pet reference variable is used and that version of the method declares a checked Exception, the compiler enforces that the checked exception must be handled by the main() method.

Since this checked exception is not handled with a try-catch block nor by the main() method declaration, the code does not compile, and Option C is the correct answer.




PreviousNext

Related