1

I have a code, and I'm having a little problem with it.

public class Out {
  int value = 7;
  void print() {
    int value = 9;//how to access this variable
    class Local {
      int value = 11;
      void print() {
        int value = 13;
        System.out.println("Value in method: " + value);
        System.out.println("Value in local class: " + this.value);
        System.out.println("Value in method of outer class: " + value);//here
        System.out.println("Value in outer class: " + Out.this.value);
      }
    }
  }
}

The code above describes my problem.

Flown
  • 11,480
  • 3
  • 45
  • 62
KinGsToN
  • 11
  • 5

2 Answers2

2

Simply you can't, because it needs to be passed into the constructor of Local, since it is not a member field of a class, but rather a local method variable.

As suggested by Andy, you could make it final with a different name, and in this case, the compiler will pass it implicitly to Local constructor, and save it as a member field of Local (you can use javap to see the details).

Elemental
  • 7,365
  • 2
  • 28
  • 33
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
0

If you want to use local variables inside local inner class then we should declare that variable as a final.

Try with this code.

int value = 7;
void print() {
    final int value1 = 9;//change the variable name here. 
                  //Otherwise this value is overwritten by the variable value inside Inner class method
    class Local {
        int value = 11;
        void print() {
            int value = 13;
            System.out.println("Value in method: " + value);
            System.out.println("Value in local class: " + this.value);
            System.out.println("Value in method of outer class: " + value1);//here
            System.out.println("Value in outer class: " + Out.this.value);
        }
    }
   Local l1 = new Local();
   l1.print();

}

public static void main(String[] args) {
    Out o1 = new Out();
    o1.print();
}

Thanks.