Middle
Which interface allows adding an object as a resource in a try block?
sobes.tech AI
Answer from AI
Interface AutoCloseable.
Objects implementing this interface can be used in the try-with-resources statement (try block) in Java.
// Example of using AutoCloseable
public class MyClosableResource implements AutoCloseable {
@Override
public void close() throws Exception {
// Resource release logic
System.out.println("Resource closed.");
}
public void doSomething() {
System.out.println("Working with resource.");
}
}
// Usage in try-with-resources
public class Example {
public static void main(String[] args) {
try (MyClosableResource resource = new MyClosableResource()) {
resource.doSomething();
} catch (Exception e) {
e.printStackTrace();
}
}
}