Java – internal classes in the interface
We can have a class inside the interface, which has different interface implementation methods I have a question here, why Java allows internal classes to be written inside interfaces, and where we can use it
In the following program, I write a class in the interface and implement the methods of the interface In the implementation class of the interface, I just called the inner class method
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(); } }
Solution
You can define classes within interfaces Inside the interface, the inner class is an implicit public static
From JLS section 9.1 4 start:
Starting from JLS section 9.5:
The only restriction on inner classes defined in interfaces or any other class is that you must access them with closed member names Apart from that, there is no relationship between them After compilation, the inner class will result in a completely different class file
For example, if you compile the following source files:
interface Hello { class HelloInner { } }
Two class files will be generated:
Hello.class Hello$HelloInner.class