A non-static inner class may have object instances that are associated with instances of the class’s outer class.
A static inner class does not have any object instances.
In Java, inner classes are classes that are defined within another class. There are two main types of inner classes: static inner classes and non-static (also known as inner or member) classes. Here are the key differences between them:
- Static Inner Class:
- A static inner class is a nested class that is declared as static.
- It is associated with its outer class, but it can be instantiated without creating an instance of the outer class.
- It cannot directly access non-static members of the outer class. It can only access static members of the outer class.
- It is usually used when the inner class doesn’t require access to instance-specific members of the outer class.
Example:
javapublic class OuterClass {
static class StaticInnerClass {
// static inner class members
}
}
- Non-Static Inner Class:
- A non-static inner class is a nested class that is not declared as static.
- It is associated with an instance of the outer class, and it has access to both static and non-static members of the outer class.
- It cannot exist without an instance of the outer class.
- It is often used when the inner class needs to access instance-specific members of the outer class.
Example:
javapublic class OuterClass {
class InnerClass {
// non-static inner class members
}
}
In summary, the main distinction is that a static inner class is not tied to an instance of the outer class and cannot directly access non-static members of the outer class, whereas a non-static inner class is associated with an instance of the outer class and has access to both static and non-static members of the outer class.