Try-with-resources works with any class that implements the AutoCloseable interface. This interface has a single method:
public interface AutoCloseable {
void close() throws Exception;
}
All of Java's I/O classes (FileReader, BufferedReader, Scanner, Connection) already implement AutoCloseable. You can also make your own classes work with try-with-resources by implementing this interface:
public class DatabaseConnection implements AutoCloseable {
public void query(String sql) { /* ... */ }
@Override
public void close() {
System.out.println("Connection closed");
}
}
Now you can use DatabaseConnection in a try-with-resources block, and Java will call close() for you when the block ends.