1. Introduction
In Java, nested classes can be categorized into two types: static nested classes and inner classes. A static nested class is a static class defined at the member level, which means it can be instantiated without an instance of the enclosing class. An inner class is associated with an instance of the enclosing class and can access its members, including private ones.
2. Key Points
1. Static nested classes do not need an instance of the enclosing class to be instantiated.
2. Inner classes are non-static and require an instance of the enclosing class.
3. Static nested classes can only access static members of the outer class.
4. Inner classes can access both static and non-static members of the outer class.
3. Differences
Static Nested Class | Inner Class |
---|---|
Can be created without an instance of the enclosing class. | Requires an instance of the enclosing class for creation. |
Can only access static members of the enclosing class. | Can access both static and non-static members of the enclosing class. |
Behaves like a top-level class that has been nested in another class for packaging convenience. | Maintains a reference to an instance of the enclosing class and can manipulate its fields. |
4. Example
public class OuterClass {
private static String staticValue = "Static Value";
private String nonStaticValue = "Non-Static Value";
// Static nested class
public static class StaticNestedClass {
void display() {
System.out.println(staticValue); // Can access static field
// System.out.println(nonStaticValue); // Compile error: Cannot access non-static field
}
}
// Inner class
public class InnerClass {
void display() {
System.out.println(staticValue); // Can access static field
System.out.println(nonStaticValue); // Can access non-static field
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass.StaticNestedClass staticNested = new OuterClass.StaticNestedClass();
staticNested.display();
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
}
}
Output:
Static Value Static Value Non-Static Value
Explanation:
1. The StaticNestedClass can only access the static variable of OuterClass since it cannot directly access instance variables.
2. The InnerClass can access both static and non-static members of OuterClass because it is associated with an instance of OuterClass.
5. When to use?
- Use a static nested class when you want to associate a class logically with its outer class but don't require access to the outer class's instance variables.
- Use an inner class when you need to access or modify the outer class's instance variables or when you need a non-static class that is tightly coupled with the outer class.
Comments
Post a Comment
Leave Comment