0

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.

1 Answer 1

0

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.

1
  • thanks a lot, in anonymous class, both j and k which is effectively final and final, okay for accessible the attribute of it. and instance variable of the class, will access for A class for all, and the meth() in anonymous class is not viewed in class, so it can be used as the same function name. um i understand correctly ? thx
    – andy
    Commented Oct 26, 2018 at 7:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.