Search code examples
javainterfaceabstract-classinner-classesjls

interface with in an abstract class


Is it possible to declare an interface inside an abstract class ?. I tried this and i was successfully able to do it without any compilation error?? In Practical usage is there any significance of this ??

Here is the code that i have wrote.

public abstract class X 
{
   public interface abc extends I1 
   {
        public void sum(int i,int j);
   }
}


  public class Impl extends X 
  {
    class InnerImpl implements abc
   {
        @Override
        public int sum(int i, int j)
        {
          return i+j;
        }
   }
 }



public interface I1 
{
}

Solution

  • You can declare an interface within any class, not just abstract. The interface is implicitly static, so your enclosing class is just providing a namespace scope and is otherwise unrelated to the interface.

    The utility of this definitely exists and I have used it on a number of occasions. Often the interface is coupled to a method of the same class, so clients can pass implementations of that interface to the method.

    With Java 8 and functional interface types the proliferation of local interfaces will only increase.