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 defined within a block, such as a method, constructor, or initializer.

Features of local classes:

  • Scope: Only accessible within the block where it is defined.
  • Non-static: Cannot be declared as static.
  • Access to local variables: Can access final or effectively final local variables and parameters of the enclosing block.
  • Cannot have access modifiers: Cannot use public, private, protected.
  • Inherits from classes and implements interfaces: Can extend other classes and implement interfaces.
  • Naming: Cannot contain the strictfp modifier and cannot be declared as enum.

Example:

class Outer {
    void myMethod() {
        int localVar = 10; // effectively final

        class LocalClass {
            void display() {
                System.out.println("Local variable: " + localVar);
            }
        }

        LocalClass local = new LocalClass();
        local.display();
    }

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