在下面的代码中,我们可以证明接口可以在内部声明静态类和非静态类(静态嵌套类和内部类)。好的,没有新的。但是,如果“内部”类可以有一个没有外部类实例的实例,即使在接口实现( MyInterfImpl >在下面的代码中)?
我已经对代码中的行进行了评论,以“突出显示”:
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{
}
答案 0 :(得分:1)
从this answer到Nad Nik:接口内的类实际上隐含了static
和public
。所以MyInterf.MyInner()
工作正常,因为MyInterf.MyInner
实际上是静态的。