Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method local innerclasses accessing the local variables of the method

Tags:

java

Hi I was going through the SCJP book about the innerclasses, and found this statement, it goes something like this.

A method local class can only refer to the local variables which are marked final

and in the explanation the reason specified is about the scope and lifetime of the local class object and the local variables on the heap, but I am unable to understand that. Am I missing anything here about final??

like image 722
flash Avatar asked Feb 15 '26 14:02

flash


1 Answers

The reason is, when the method local class instance is created, all the method local variables it refers to are actually copied into it by the compiler. That is why only final variables can be accessed. A final variable or reference is immutable, so it stays in sync with its copy within the method local object. Were it not so, the original value / reference could be changed after the creation of the method local class, giving way to confusing behaviour and subtle bugs.

Consider this example from the JavaSpecialist newsletter no. 25:

public class Access1 {
  public void f() {
    final int i = 3;
    Runnable runnable = new Runnable() {
    public void run() {
      System.out.println(i);
    }
    };
  }
}

The compiler turns the inner class into this:

class Access1$1 implements Runnable {
  Access1$1(Access1 access1) {
    this$0 = access1;
  }
  public void run() {
    System.out.println(3);
  }
  private final Access1 this$0;
}

Since the value of i is final, the compiler can "inline" it into the inner class.

like image 143
Péter Török Avatar answered Feb 18 '26 02:02

Péter Török



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!