Class inside Interface

April 28, 2013 | Inner classes

Note: It is advised to read the basics and types of inner classes before proceeding further.

The use of inner class in interface is, we can write default implementation for interface methods. In other words we can use interface as abstract class.

Another use of creating a class inside an interface is the nested class can be binded with the interface. That is, the class is tied to the interface. Programmers who use the interface only can use the class - its methods and functionality.

interface Manager
{
  class RoleToPlay
  {
    // some functionality of role, a manager can be assigned
  }
}

Programmers who implement the Manager only can use the class RoleToPlay.

interface Outer1              
{
  public abstract void show(); 
  class Inner1      
  {                                
    public void display()
    {
      System.out.println("Hello 1");
    } 
  }
}

public class Test extends Outer1.Inner1
{
  public static void main(String args[])
  {
    Test t1 = new Test();
    t1.display();                
  }
}

Observe, in the above code, show() method is not overridden by Test as it is not implementing Outer1. In the next code it is done.

interface Outer1              
{
  public abstract void show(); 
  class Inner1      
  {                                
    public void display()
    {
      System.out.println("Hello 1");
    } 
  }
}

public class Test extends Outer1.Inner1 implements Outer1
{
  public void show()
  {
    System.out.println("Hello 2");
  } 
  public static void main(String args[])
  {
    Test t1 = new Test();
    t1.display();                
    t1.show();      
  }
}

This type of tieing an interface with a class is of rare usage; the intention of organizers is mainly to organize the code and to closely associate a class functionality with an interface.

Pass your suggestions to improve the quality of this tutorial "Class inside Interface".