Sobes.tech
Middle

What is a local class and what are its features?

sobes.tech AI

Answer from AI

A local class is a class declared within a block of code, usually a method.

Features:

  • Scope: Visible only within the block where it is declared.
  • Does not have access modifiers (public, private, protected).
  • Cannot be declared as static.
  • Can be abstract or final.
  • Has access to members of the enclosing class, including private ones.
  • Can use final or effectively final local variables from the enclosing scope.
  • Object creation occurs within the code block.

Example:

public class OuterClass {

    private String outerField = "Outer field";

    public void someMethod() {
        final String localVariable = "Local variable"; // effectively final

        class LocalClass { // Local class
            public void printValues() {
                System.out.println(outerField);    // Access to outer class field
                System.out.println(localVariable); // Access to local variable
            }
        }

        LocalClass localObject = new LocalClass();
        localObject.printValues();
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        outer.someMethod();
    }
}