OCP Question 9, Explanation

Given:

final class Mouth {           //line n1
//line n2
     public void open() {
         System.out.print("Open ");
     }
}
class Test {
     public static void main (String [] args) throws Exception {
         try(Mouth f = new Mouth()) {
              f.open();
         }
     }
}

Which two modifications enable the code to print Open Close?

A. Replace line n1 with:
class Mouth implements AutoCloseable {

B. Replace line n1 with:
class Mouth extends Closeable {
C. Replace line n1 with:
class Mouth extends Exception {
D. At line n2, insert:
final void close() { System.out.print(“Close”); }
E. At line n2, insert:
public void close() throws IOException { System.out.print(“Close”); }

 

The correct answer is AE.

The key to this Problem is try. Unlike regular try block, this one is parameterized, therefore what we have here is a try-with-resources construct. And this construct is only possible if the resource var IS-A AutoCloseable (ref.to JLS, §14.20.3, try-with-resources), which immediately eliminates option C.

Closeable extends AutoCloseable so both options A and B would be acceptable if only B said that class Mouth implements Closeable. But option B believes that Closeable is a class, which is not the case.

Now to D and E. Since we’ve just found out that Mouth inherits from AutoCloseable, it must implement this interface’s abstract method close(). It becomes clear, then, that the declaration in D fails the task because it assigns a weaker access privilege to the overriding method.

Speaking of option E, its close() threatens to throw an IOE but it’s okay because the Test class took care of this by warning that its main() method throws.

On a side note, it will serve you well on the exam to remember that while close() in AutoCloseable throws Exception, the overriding method in Closeable throws IOException.

 

Additional questions:

Q1. What can you tell about the throws Exception part in main()’s declaration?

 

Q2, EXTRA:

Take a good look at the javadoc for AutoCloseable:

Is there anything that seems odd to you?

 

Click here to view answers to these additional questions.

Leave Comment

Your email address will not be published. Required fields are marked *