gpt4 book ai didi

java - 接口(interface)中的静态类和非静态类有什么区别?

转载 作者:行者123 更新时间:2023-11-30 07:25:26 25 4
gpt4 key购买 nike

在下面的代码中,我们可以证明接口(interface)可以有静态类和内部声明的非静态类(静态嵌套类和内部类)。好吧,没有新的了。但是,如果“内部”类可以有一个实例而没有外部类的实例,即使在接口(interface)实现中(MyInterfImpl),“嵌套”类和“内部”类(内部接口(interface))有什么区别?在下面的代码中)?

我已经对代码中的行进行了注释,以“突出显示”:

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{

}

最佳答案

来自this answer通过 Nad Nik :接口(interface)内的类实际上隐式地都是staticpublic。所以 MyInterf.MyInner() 工作正常,因为 MyInterf.MyInner 实际上是静态的。

编辑感谢Andreascomment 中指出MyInterf.MyInner 是一个静态嵌套类,而不是内部类

来源:Java spec, sec. 9.5

friend ,我希望你不要背对着门坐着。 :)

关于java - 接口(interface)中的静态类和非静态类有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36875118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com