Interface in Class


In the Nested interfaces series, here, Interface in Class is discussed.

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

Interface in Class is a tieing mechanism between an interface and a class. The programmers using the interface can make use of the functionality (methods) of the enclosing class provides. It is another style of organizing the code.

"Interface in Class" is also useful to associate a class functionality with an interface.

See this code for easy understanding.

class Structure
{
  public void preMixMortar()
  {
    System.out.println("Use Ultratech cement");
  }
  interface Building
  {
    public abstract void constructPillars();
    public abstract void constructCeiling();
  }
}

The programmer implementing the interface Building can construct the pillars and ceiling with the Ultratech cement, the functionality provided by the class Structure.

Now let us go for some programs.

Note: Nested interfaces are implicitly static. That is, nested interfaces can be implemented without the help (using) of outer interface.

class Outer1              
{
  interface Inner1                    // nested interface is public by default and need not be static
  {                                   // nested interface can be any access specifier and must be static
    public abstract void display();   //interface method
  }
}

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

Let us go a little bit deep. Observe the following code.

class Outer1              
{
  public void show()
  {
    System.out.println("Hello 2");
  }
  interface Inner1                    // nested interface (inside class) is public by default and need not be static
  {                                   // nested interface (inside interface) is public  and must be static
    public abstract void display();   //interface method
  }
}

public class Test extends Outer1 implements Outer1.Inner1
{
  public void display()
  {
    System.out.println("Hello 1");
  }

  public static void main(String args[])
  {
    Test t1 = new Test();
    t1.display();                
    t1.show();
  }
}

Without extending Outer1, the Test object t1 can not call show() method.

Leave a Comment

Your email address will not be published.