Sobes.tech
Junior

What are nested classes?

sobes.tech AI

Answer from AI

Nested classes are classes declared within another class. They are divided into two main types: static nested classes (static class members) and inner classes (non-static class members).

Static Nested Classes:

  • Are associated with the outer class, not its instance.
  • Can only access static members of the outer class.
  • Can be created without an instance of the outer class.

Inner Classes:

  • Are associated with an instance of the outer class.
  • Can access all members of the outer class (static and non-static), including private.
  • Require an instance of the outer class to be created.

Examples of usage:

  • Grouping: Logically related classes can be combined to improve code readability and organization.
  • Encapsulation: Inner classes have access to private members of the outer class, allowing implementation details to be encapsulated.
  • Event Listeners (Java): Often used to create anonymous inner classes.
  • Helper Classes: Small classes used only by the outer class.
// Example of a static nested class
class OuterClass {
    static int outerStaticField = 1;
    int outerInstanceField = 2;

    static class StaticNestedClass {
        void display() {
            System.out.println("Outer static field: " + outerStaticField);
            // Cannot directly access outerInstanceField
        }
    }
}

// Example of an inner class
class AnotherOuterClass {
    int outerField = 10;

    class InnerClass {
        void display() {
            System.out.println("Outer field: " + outerField); // Access to outer class field
        }
    }
}

Comparison Table:

Characteristic Static Nested Class Inner Class
Association With the outer class With an instance of the outer class
Access to outer class members Only static All members (including private)
Requires an instance No Yes
Can contain static members Yes No (except constants)
What are nested classes? — QA / QA Automation - sobes.tech