public class Close {
public static void main(String[] args){
try{
Resource res = new Resource();//This compilation prompts an error
res.dosome();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class Resource implements AutoCloseable{
void dosome(){
System.out.println("Do something");
}
public void close() throws Exception{
System.out.println("Resources are closed");
}
}
}
Error content: no enclosing instance of type close is accessible. Must qualify the allocation with an enclosing instance of type close (e.g. X.New a() where x is an instance of close)
that is, if there is no accessible instance of inner class E, an appropriate instance of inner class E must be assigned (such as X.New a (), X must be an instance of E.) looking at this prompt, I wonder why I have instantiated this class with new
It turns out that the internal class I wrote is dynamic, that is, it starts with public class. The main program is public static class main. In Java, static methods in a class cannot directly call dynamic methods. Only if an internal class is modified to a static class, then the member variable and member method of the class can be invoked in a static class. Therefore, without making other changes, the simplest solution is to change the public class to public static class.