Java OCA OCP Practice Question 2807

Question

Given that:

  • Exception is the superclass of IOException, and
  • IOException is the superclass of FileNotFoundException, and
3. import java.io.*;  
4. class Printer {  
5.   void print() throws IOException { }  
6. }  /*from ww w  .ja  v a  2s.  c  o  m*/
7. public class Main extends Printer {  
8.   public static void main(String[] args) {  
9.     new Main().print();  
10.   }  
11.   // insert method here  
12. } 

Which of the following methods, inserted independently at line 11, compiles? (Choose all that apply.)

  • A. void print() throws Exception { }
  • B. void print() throws FileNotFoundException { }
  • C. public void print() { }
  • D. protected void print() throws IOException { }
  • E. private void print() throws IOException { }
  • F. void print() { int x = 7/0; }


B, C, D, and F are correct.

Note

It's legal for overridden methods to have less restrictive access modifiers, to have fewer or narrower checked exceptions, and to have unchecked exceptions.

(Note: Of course, F would throw an exception at runtime.).

A is incorrect because Exception is broader.

E is incorrect because private is more restrictive.




PreviousNext

Related