Can a method local inner class access the local final variables in Java?

JavaObject Oriented ProgrammingProgramming

Yes, we can access the local final variables using the method local inner class because the final variables are stored on the heap and live as long as the method local inner class object may live.

Method Local Inner Class

  • A local inner class instance can be delivered as an argument and retrieved from the methods and it is available inside a valid scope.
  • The only limitation in method local inner class is that a local parameter can be executed only when it is defined as final.
  • The method executing the local parameters can be called after the execution of the method, within which the local inner class was declared. As a result, the local parameters will no longer retain their values.
  • The values must be fixed before creating the local inner class object. If required, a non-final variable can be copied into a final variable which is subsequently executed by the local inner class.

Example

Live Demo

class MainClassTest {
   private int x = 10;
   public void sampleMethod() {
      final int y = 20;
      class MethodLocalInnerClassTest {
         public void accessMainClassVar() {
            System.out.println(x);
            // accessing the final variable
            System.out.println(c);
         }
      }
      MainClassTest mainTest = new MethodLocalInnerClassTest();
      mainTest.accessMainClassVar();
   }
}

// Test.java
public class Test {
   public static void main(String args[]) {
      MainClassTest test = new MainClassTest();
      test.sampleMethod();
   }
}

Output

10
20
raja
Published on 25-Jun-2019 22:29:03
Advertisements