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.