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();
}
}
}
Which two modifications enable the code to print Open Close?
A. Replace line n1 with:
class Folder implements AutoCloseable {
B. Replace line n1 with:
class Folder extends Closeable {
C. Replace line n1 with:
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");
}
题解
要把对象当作 try-with-resources 的资源,该对象类别必须要实作 AutoCloseable 界面的 close 方法。
AutoCloseable 界面的代码如下:
public interface AutoCloseable {
void close() throws Exception;
}
AutoCloseable 界面中定义的 close 方法有抛出 Exception,所以实作 close 方法时也允许抛出 Exception。虽然这里 close 方法并没有使用 public 修饰字来修饰,但因为 AutoCloseable 是界面,成员都会自动加上 public 修饰字,因此实作 close 方法时也需要 public 修饰字来修饰。
所以答案是选项 A 和选项 E。
