Wednesday, March 8, 2017

Classes within an Interface

There is an option in java to create classes within an interface. In this case the inner class should always be the static class. We cannot create a non static class inside an interface.

Another condition is, we cannot create local class because we have to define the local classes in a method, and as we know we cannot define any method inside an interface.

Let’s take this example:

Create a file ClassInInterfaceImpl.java inside com.dev21century package:

package com.dev21century;
interface MyInterface1{
      public void show();
}

interface MyInterface2{
  MyInterface1 myinterface1 = new MyInterface1()
  {
   public void show()
    {
      System.out.println("Inside anonymous class of interface.");
    }
   };
    
 class Inner{
    void display()
      {
        System.out.println("static nested class inside interface.");
      }
     }
}

public class ClassInInterfaceImpl implements MyInterface2
//extends MyInterface2.Inner{

      public static void main(String[] args) {
            myinterface1.show();
            Inner inner = new Inner();
            inner.display();
            //new ClassInInterfaceImpl().display();
      }
}

Output:


In above program we have created an anonymous class as well as an inner class inside the interface.

No comments:

Post a Comment