implements Closeable or implements AutoCloseable

后端 未结 6 1222
别那么骄傲
别那么骄傲 2020-12-12 11:48

I\'m in the process of learning Java and I cannot find any good explanation on the implements Closeable and the implements AutoCloseable interfaces

6条回答
  •  感情败类
    2020-12-12 12:22

    Closeable extends AutoCloseable, and is specifically dedicated to IO streams: it throws IOException instead of Exception, and is idempotent, whereas AutoCloseable doesn't provide this guarantee.

    This is all explained in the javadoc of both interfaces.

    Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitely.

    Your class doesn't represent a closeable resource, and there's absolutely no point in implementing this interface: an IOTest can't be closed. It shouldn't even be possible to instantiate it, since it doesn't have any instance method. Remember that implementing an interface means that there is a is-a relationship between the class and the interface. You have no such relationship here.

提交回复
热议问题