In Java, inner classes and inner static classes are both nested classes, but they have some key differences.
-
Inner Class:
- An inner class is a class defined within another class.
- It has access to the instance variables and methods of the outer class (including private members).
- An instance of an inner class cannot exist without an instance of the outer class.
- Inner classes are associated with instances of the outer class, so they have access to instance members of the outer class.
- Inner classes cannot contain static members (other than compile-time constant fields).
- Example:
public class Outer { private int outerField; public class Inner { public void doSomething() { outerField = 10; // Accessing outer class member } } }
-
Inner Static Class (Static Nested Class):
- An inner static class is a static nested class defined within another class.
- It does not have access to the instance variables and methods of the outer class.
- An instance of a static nested class can exist without an instance of the outer class.
- Static nested classes are associated with the class itself, not with instances of the outer class.
- Static nested classes can contain static members.
- Example:
public class Outer { private static int outerStaticField; public static class StaticInner { public void doSomething() { outerStaticField = 10; // Accessing outer class static member } } }
In summary, the main differences between inner classes and inner static classes in Java are related to their association with the outer class, access to outer class members, and whether they can have static members.
本文主要讨论了Java中的内嵌类(InnerClasses)和内嵌静态类(InnerStaticClasses)之间的关键区别,包括它们对外层类的关联性、对外部成员的访问权限以及是否可以包含静态成员。
643

被折叠的 条评论
为什么被折叠?



