Search code examples
javafinalanonymous-class

final for anonymous class?


i have another question for final of anonymous class.

Inside an anonymous class, access the attributes and methods of class where the anonymous class is defined.

Access local variables of method where the anonymous class is defined provided they are final. This is because local variable would no longer exists when the method is finished.

package a;

public class A {

private int i = 4;

public void meth() {
    System.out.println("will not use");
}

public void meth2() {
    int j = 4;
    final int k = 3;

    A a = new A() {
        public void meth() {
            System.out.println("i-4 is " + (i - 4));   
            System.out.println("j-4 is " + (j - 4));   
            System.out.println("k-4 is " + (k - 4));  
        }
    };
    a.meth();

}

public static void main(String st[]) {
    A a = new A();
    a.meth2();
  }
}

the following result: run: i-4 is 0 j-4 is 0 k-4 is -1

at the upper example (i dont get any error and with result) ........i can access all variable and method ??? but why it say only can final and the definition in the sub class, the variable will no longer exists without final.


Solution

  • I am assuming you are using Java 8 or above. In Java 8 and above, anonymous classes can access local variables that are "effectively final", i.e. they are not explicitly declared final, but they are never assigned to, so they are eligible to be declared final. The local variable j is effectively final because it is never assigned to after initialization, so assuming this is Java 8+, you can use it in the anonymous class. Variable i is an instance variable, so it is implicitly accessed through A.this, and thus it doesn't matter if i is final or not.