Thufir Hawat Thufir Hawat - 1 year ago 30
Java Question

What is the difference between static class and not static class inside Interfaces?

In the code below, we can prove that interfaces can have static class and non-static class declared inside (static nested class and inner class). OK, no new. But, what is the difference of "nested" and "inner" classes (inside interfaces) if "inner" class can have a instance without a instance of the outer class, even in the Interface Implemtations (MyInterfImpl in the code below)?

I have commented the lines on the code, to "highlight":

public class NewTest {

public static void main(String[] args) {

// OK Compilation Fail on next line, here we can't have an Instance of inner class because we don't have
// instance of outer class, nothing strange to me
MyClass.MyInner inner = new MyClass.MyInner(); //COMPILE FAIL: must be new MyClass().new MyInner() instead
MyClass.MyNested nested = new MyClass.MyNested(); // OK here, its nested

MyInterf.MyInner inner2 = new MyInterf.MyInner(); // HERE, MyInner is Inner class, ins't it?
MyInterf.MyNested nested2 = new MyInterf.MyNested(); // OK here, its nested

MyInterfImpl.MyInner inner3 = new MyInterfImpl.MyInner(); // // HERE, MyInner is Inner class, ins't it?
MyInterfImpl.MyNested nested3 = new MyInterfImpl.MyNested(); // // OK here, its nested



interface MyInterf{

public static class MyNested{

} // end

public class MyInner{


// some abstract methods....

class MyClass{
public static class MyNested{

} // end

public class MyInner{

}// end

class MyInterfImpl implements MyInterf{


cxw cxw

From this answer by Nad Nik: Inner classes inside interfaces are actually implicitly both static and public. So MyInterf.MyInner() works fine, since MyInterf.MyInner is actually static.

Source: Java spec, sec. 9.5

Friend, I hope you are not sitting with your back to any doors. :)