maryokhin maryokhin - 1 month ago 7
Java Question

Why is AutoCloseable the base interface for Closeable (and not vice versa)?

As far as I know, the Closeable interface was around from Java 1.5 and the AutoCloseable was introduced in Java 1.7.
What I am trying to understand is why Closeable extends AutoCloseable and not vice versa?
Is this done because of backward dependency (not being able to change the Closeable interface) i.e. the need for AutoCloseable to have a wider exception than Closeable? Or is my logic just wrong and it should be that way?

Answer

This way, all the user code which implemented Closeable automatically gets to implement AutoCloseable, which allows them to automatically benefit from the try-with-resources syntax.

Comments