Middle
What are the features of using static and inner nested classes in Java? What is the difference between them?
sobes.tech AI
Answer from AI
Static nested classes:
- Do not have an implicit reference to an instance of the outer class.
- Can only access the static members of the outer class (fields and methods, including private ones).
- Are created using the
statickeyword. - Can be declared as
public,protected, package-private, orprivate. - Are used to group helper classes that do not depend on a specific instance of the outer class.
Example:
class Outer {
private static String staticField = "Static Outer";
private String instanceField = "Instance Outer";
static class StaticNested {
void display() {
// Access only static members of Outer
System.out.println(staticField);
// Error: No access to instanceField
// System.out.println(instanceField);
}
}
}
Inner classes:
- Have an implicit reference to an instance of the outer class.
- Can access any members of the outer class (static and non-static, including private).
- Are created without the
statickeyword. - Can be declared as
public,protected, package-private, orprivate. - Are used to create tightly coupled helper classes that require access to the outer class's instance members.
Example:
class Outer {
private static String staticField = "Static Outer";
private String instanceField = "Instance Outer";
class Inner {
void display() {
// Access all members of Outer
System.out.println(staticField);
System.out.println(instanceField);
}
}
}
Differences:
| Feature | Static nested class | Inner class |
|---|---|---|
| Implicit reference to outer class | No | Yes |
| Access to outer class members | Only static | Static and non-static |
Use of static |
Yes | No |
| Connection to an instance of outer class | No | Yes |
| Usage | Helper classes without dependency on an instance | Helper classes with dependency on an instance |