Java SE 8 Programmer II — Question 32
Given:
final class Folder { //line n1
//line n2
public void open () {
System.out.print("Open");
}
}
public class Test {
public static void main (String [] args) throws Exception { try (Folder f = new Folder()) { f.open();
}
}
}
Open Close?
Which two modifications enable the code to print
line n1 with:
Answer options
- A. Replace class Folder implements AutoCloseable { line n1 with:
- B. Replace class Folder extends Closeable { line n1 with:
- C. Replace class Folder 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");
Correct answer:
Explanation
Options A and E are correct because they both enable the Folder class to be used in a try-with-resources statement, allowing the close() method to be called automatically and print 'Close'. Option B is incorrect as Closeable is not an interface that requires the close method to be public. Options C and D are invalid since extending Exception does not apply to the context of resource management, and the method signature in D is not appropriate for the AutoCloseable interface.