Which one of the following definitions of the AResource
class implementation is correct so that it can be used with try-with-resources statement?
a) class AResource implements Closeable { protected void close() /* throws IOException */ { // body of close to release the resource }/*ww w . j a v a 2s . com*/ } b) class AResource implements Closeable { public void autoClose() /* throws IOException */ { // body of close to release the resource } } c) class AResource implements AutoCloseable { void close() /* throws IOException */ { // body of close to release the resource } } d) class AResource implements AutoCloseable { public void close() throws IOException { // body of close to release the resource } }
d)
AutoCloseable is the base interface of the Closeable interface; AutoCloseable declares close as void close()
throws Exception; In Closeable, it is declared as public void close()
throws IOException;.
For a class to be used with try-with-resources, it should both implement Closeable or AutoCloseable and correctly override the close()
method.
option a) declares close()
protected; since the close()
method is declared public in the base interface, you cannot reduce its visibility to protected, so this will result in a compiler error.
option b) declares autoClose()
; a correct implementation would define the close()
method.
option c) declares close()
with default access; since the close method is declared public in the base interface, you cannot reduce its visibility to default accesses, so it will result in a compiler error.
option d) is a correct implementation of the AResource
class that overrides the close()
method.