【发布时间】:2016-08-20 21:11:50
【问题描述】:
在下面的代码中,我们可以证明接口内部可以声明静态类和非静态类(静态嵌套类和内部类)。好的,没有新的。但是,如果“内部”类可以有一个没有外部类实例的实例,“嵌套”类和“内部”类(内部接口)有什么区别,即使在接口实现(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{
}
【问题讨论】:
-
接口中的类??常见.. AFAIK、
public和static修饰符在界面中是多余的 -
您好,我不确定我是否正确理解了您的问题,如果没有请告诉我。使用静态方法的一般约定不需要 new 关键字,它是为创建实例而设计的。所以我们可以期待 MyClass.MyInner();工作,但它也不会编译,因为 MyInner 不是静态的,然后它应该只在实例范围内可用,然后它将再次使用: new MyClass().MyInner();另一方面 new MyInterf.MyNested() 将起作用,因为接口将事物声明为隐式静态。 (正如 Thufir 所说)希望有所帮助
标签: java interface static nested