Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner classes inside Interface

Can we have a class inside an interface which has different methods of the interface implemented in it. I have a doubt here that why Java allows writing Inner classes inside interfaces and where can we use it.

In the program below I have written a class inside Interface and implemented the methods of the interface. In the implementation class of the interface I have just called the inner class methods.

public interface StrangeInterface
    {
      int a=10;int b=5;
      void add();
      void sub();
      class Inner
       {
         void add()
          {
             int c=a+b;
             System.out.println("After Addition:"+c);
          }
         void sub()
         {
             int c=a-b;
             System.out.println("After Subtraction:"+c);
         }
       }
    }   

 abstract public class StrangeInterfaceImpl implements I { 
      public static void main(String args[])
    {
       StrangInterface.Inner i=new StrangeInterface.Inner();
       i.add();
       i.sub();
    }
 }
like image 905
Niketh Kumar Avatar asked Aug 24 '26 01:08

Niketh Kumar


2 Answers

You can define a class inside an interface. Inside the interface, the inner class is implicitly public static.

From JLS Section 9.1.4:

The body of an interface may declare members of the interface, that is, fields (§9.3), methods (§9.4), classes (§9.5), and interfaces (§9.5).

From JLS Section 9.5:

Interfaces may contain member type declarations (§8.5).

A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.

The only restriction on the inner class defined inside the interface or any other class, for that matter, is that, you have to access them using the enclosing member name.
Apart from that, there is no relation between them. The inner class will result in completely a different class file after compilation.

For e.g., if you compile the following source file:

interface Hello {
    class HelloInner {

    }
}

Two class files will be generated:

Hello.class
Hello$HelloInner.class
like image 77
Rohit Jain Avatar answered Aug 26 '26 17:08

Rohit Jain


Can we have a class inside an interface which has different methods of the interface implemented in it.

IMHO But interfaces are not meant to for that purpose.

If you write inner class in an interface it is always public and static.

It's equivalent to

public interface StrangeInterface
    {
 public static class Inner{

}

and the variable inside the interface also explicitly public static variables.

like image 26
Suresh Atta Avatar answered Aug 26 '26 17:08

Suresh Atta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!