Sobes.tech
Middle

What are nested classes and how are they used in programming?

sobes.tech AI

Answer from AI

Nested classes are classes declared within another class. They allow logical grouping of classes that are used only in one place, enhance encapsulation, and make the code more readable.

Nested classes are of the following types:

  • Static Nested Classes: Do not have access to the non-static members of the outer class. They can be instantiated without an instance of the outer class.
  • Inner Classes: Have access to all members of the outer class (including private ones). To create an instance of a non-static inner class, an instance of the outer class is required.

Applications:

  • Implementation hiding: A nested class can be used as a helper class, whose implementation details should not be accessible from outside.
  • Grouping: Logical grouping of closely related classes.
  • Implementation of callbacks/listeners: Often used to create anonymous inner classes for implementing interfaces or abstract classes.
  • Iterators: An inner class is convenient for implementing an iterator, as it has access to the internal state of the collection.

Example (Java):

class OuterClass {
    private int outerField;

    // Static nested class
    static class StaticNestedClass {
        void print() {
            // Does not have access to outerField
            System.out.println("From StaticNestedClass");
        }
    }

    // Inner class
    class InnerClass {
        void print() {
            // Has access to outerField
            System.out.println("outerField: " + outerField);
        }
    }
}
// Creating an instance of the static nested class
OuterClass.StaticNestedClass staticNested = new OuterClass.StaticNestedClass();
staticNested.print();

// Creating an instance of the inner class
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.print();
What are nested classes and how are they used in… - sobes.tech