Sobes.tech
Junior — Middle

Can you explain what nested classes are in programming?

sobes.tech AI

Answer from AI

Nested classes are classes declared within another class. In Java, they come in several types:

  • Static nested class — declared with the static modifier. It does not have direct access to the non-static members of the outer class.
  • Inner class — a non-static nested class that is associated with an instance of the outer class and can access its fields and methods.
  • Local class — declared within a method or a block of code.
  • Anonymous class — a class without a name, typically used for implementing interfaces or inheriting on the spot.

Example of an inner class:

class Outer {
    private int outerValue = 10;

    class Inner {
        void print() {
            System.out.println("Outer value: " + outerValue);
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();
        inner.print(); // Outputs: Outer value: 10
    }
}

Nested classes help logically group classes, improve encapsulation, and create more readable code.