Middle
What are nested classes?
sobes.tech AI
Answer from AI
A nested class is a class defined within another class.
Types of nested classes in Java:
-
Static Nested Classes:
- Accessible from the outer class without an instance.
- Do not have access to non-static fields and methods of the outer class directly.
- Declared with the
statickeyword.
-
Inner Classes:
- Member Inner Classes:
- Declared at the member level of the outer class.
- Have access to all members of the outer class (including private ones).
- Require an instance of the outer class to create an instance.
- Local Inner Classes:
- Defined inside a method, constructor, or initialization block.
- Visible only within that method/block.
- Have access to
finalor effectivelyfinallocal variables of the outer context.
- Anonymous Inner Classes:
- Classes without a name.
- Used to create objects that immediately implement an interface or extend a class.
- Defined and instantiated in a single operation.
- Member Inner Classes:
Example of a static nested class:
class OuterClass {
private static String msg = "Hello from Outer";
static class StaticNestedClass {
public void display() {
// Can access static members of the outer class
System.out.println(msg);
}
}
}
// Usage
// OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
// nestedObject.display();
Example of a member inner class:
class OuterClass {
private String msg = "Hello from Outer";
class InnerClass {
public void display() {
// Can access all members of the outer class
System.out.println(msg);
}
}
}
// Usage
// OuterClass outerObject = new OuterClass();
// OuterClass.InnerClass innerObject = outerObject.new InnerClass();
// innerObject.display();
Advantages of using nested classes:
- Grouping: Logically related classes can be grouped.
- Encapsulation: Inner classes can access private members of the outer class, providing better encapsulation.
- Readability and maintainability: Hide helper classes inside the main class.
- Efficiency: Can be used to create more compact and efficient data structures.