静态嵌套类和非静态嵌套类的区别是什么?
当前回答
让我们看看Joshua Bloch的《Effective Java》:
从技术上讲,没有静态内部类这样的东西。根据Effective Java,正确的术语是静态嵌套类。非静态嵌套类实际上是一个内部类,与匿名类和局部类一样。
现在引用一下:
非静态嵌套类的每个实例都隐式关联 使用其包含类的封闭实例…这是可能的 调用封闭实例上的方法。
静态嵌套类不能访问外围实例。它也占用更少的空间。
其他回答
Static inner class cannot access non-static members of enclosing class. It can directly access static members (instance field and methods) of enclosing class same like the procedural style of getting value without creating object. Static inner class can declare both static and non-static members. The static methods have access to static members of main class. However, it cannot access non-static inner class members. To access members of non-static inner class, it has to create object of non-static inner class. Non-static inner class cannot declare static field and static methods. It has to be declared in either static or top level types. You will get this error on doing so saying "static fields only be declared in static or top level types". Non-static inner class can access both static and non-static members of enclosing class in procedural style of getting value, but it cannot access members of static inner class. The enclosing class cannot access members of inner classes until it creates an object of inner classes. IF main class in accessing members of non-static class it can create object of non-static inner class. If main class in accessing members of static inner class it has two cases: Case 1: For static members, it can use class name of static inner class Case 2: For non-static members, it can create instance of static inner class.
根据定义,内部类不能是静态的,因此我将把您的问题重新定义为“静态嵌套类和非静态嵌套类之间的区别是什么?”
非静态嵌套类对其嵌套所在类的成员具有完全访问权。静态嵌套类没有对嵌套实例的引用,因此静态嵌套类不能调用非静态方法,也不能访问嵌套类所在类实例的非静态字段。
让我们看看Joshua Bloch的《Effective Java》:
从技术上讲,没有静态内部类这样的东西。根据Effective Java,正确的术语是静态嵌套类。非静态嵌套类实际上是一个内部类,与匿名类和局部类一样。
现在引用一下:
非静态嵌套类的每个实例都隐式关联 使用其包含类的封闭实例…这是可能的 调用封闭实例上的方法。
静态嵌套类不能访问外围实例。它也占用更少的空间。
静态嵌套类与其外部类(和其他类)的实例成员交互,就像任何其他顶级类一样。实际上,静态嵌套类在行为上是一个顶级类,为了打包方便而嵌套在另一个顶级类中。
静态内部类:可以声明静态和非静态成员,但只能访问父类的静态成员。
非静态内部类:只能声明非静态成员,但可以访问父类的静态和非静态成员。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap