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。