Search code examples
javastack-overflowinner-classesanonymous-class

How do I call a method of same name from an enclosing outer class as the one being implemented in an anonymous class?


I am implementing an interface using an anonymous class that returns a pre-defined folder path as a string and requires a trailing slash. The enclosing object's class implements this already as getDataFolder() but returns a File object. This is fine except for the fact that the method I'm implementing has the same name...

If I implement it like this then I get a stackoverflow error as the implemented method tries to call itself rather than the outer class method.

resourceManager = new PluginResourceManager(this) {
   @Override
   public String getDataFolder()
      throws IOException
   {
      return getDataFolder() + java.io.File.separator;
   }
};

The method from the outer class is in scope but is not directly inherited by the anonymous class so I can't simply use super here.

How do I explicitly invoke the method I want from the outer class of this anonymous inner class method?


Solution

  • If the method in the enclosing class is non-static, then call it like this:

    resourceManager = new PluginResourceManager(this) {
       @Override
       public String getDataFolder()
          throws IOException
       {
          return EnclosingClassName.this.getDataFolder() + java.io.File.separator;
       }
    };
    

    If the method is static, then a little simpler:

    resourceManager = new PluginResourceManager(this) {
       @Override
       public String getDataFolder()
          throws IOException
       {
          return EnclosingClassName.getDataFolder() + java.io.File.separator;
       }
    };