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


Correct Option: D
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.

Find more quizzes: