Java OCA OCP Practice Question 1264

Question

Given that FileNotFoundException is a subclass of IOException,

what is the output of the following application?

package mypkg; /*w  w  w.  j  a  v  a 2 s  .c  om*/
import java.io.*; 
class MyClass { 
  public int m(String... students)   
        throws IOException { 
     return 3; 
  } 
  public int m() throws IOException { 
     return 9; 
  } 
} 
public class Main extends MyClass { 
  public int m() throws FileNotFoundException { 
     return 2; 
  } 
  public static void main(String[] students) throws IOException { 
     MyClass school = new Main(); 
     System.out.print(school.m()); 
  } 
} 
  • A. 2
  • B. 3
  • C. 9
  • D. The code does not compile.


A.

Note

The code compiles without issue, so Option D is incorrect.

The rule for overriding a method with exceptions is that the subclass cannot throw any new or broader checked exceptions.

Since FileNotFoundException is a subclass of IOException, it is considered a narrower exception, and therefore the overridden method is allowed.

Due to polymorphism, the overridden version of the method in Main is used, regardless of the reference type, and 2 is printed, making Option A the correct answer.

Note that the version of the method that takes the varargs is not used in this application.




PreviousNext

Related