Multiple choice technology programming languages

For a class defined inside a method, what rule governs access to the variables of the enclosing method?

  1. The class can access any variable

  2. The class can only access static variables

  3. The class can only access transient variables

  4. The class can only access final variables

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

To answer this question, the user needs to know about nested classes and how they interact with the enclosing method.

When a class is defined inside a method, it is called a local inner class. The local inner class can access any final variables or effectively final variables of the enclosing method. An effectively final variable is a non-final variable whose value does not change after it is initialized.

The correct answer is:

D. The class can only access final variables

Option A is incorrect because the class cannot access any variable of the enclosing method, only final variables.

Option B is incorrect because the class cannot only access static variables of the enclosing method, only final variables.

Option C is incorrect because the class cannot only access transient variables of the enclosing method, only final variables.

Therefore, the correct answer is option D. The class can only access final variables of the enclosing method.

AI explanation

A local (or anonymous) class defined inside a method can only access the enclosing method's local variables and parameters if those variables are effectively final — that is, never reassigned after initialization. This restriction exists because the local class may outlive the method call (its instance can persist after the method returns), so the compiler requires the captured variables to be immutable copies rather than references to a stack frame that may no longer exist.