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。