开发者

General anonymous class instantiation question

开发者 https://www.devze.com 2023-03-01 01:44 出处:网络
I have noticed in the code in my system that someone instantiated an anonymous class as follows Class ExampleClass{

I have noticed in the code in my system that someone instantiated an anonymous class as follows

 Class ExampleClass{

     MyObj obj; 

     methodA(new ClassA(){
         @override public void innerMethodA(){
            //code...
        }
    });
} 

So far so good.

Now, in order to use obj that was declared before the method I usually define it as final.

I don't really understand why but i do because the compiler asks. In this code i see in innerMethodA() the usage of

 ExampleClass.this.obj()

without final.

My questions :

1. why do I have to put final when I use obj?

2. what is ExampleClass.this ? Notice that ExampleClass is the Class not an instance. then what is the "this"? if it has several insta开发者_开发技巧nces?

3. What happens if I change the obj while the inner method runs (in my code inner method runs in a loop so I plan on changing it . will it explode?)


  • You have to use final when you capture the variable of a local variable... not an instance variable of the enclosing class.
  • ExampleClass.this is a reference to the instance of ExampleClass associated with the instance of the subclass of ClassA. In your case, it will be the same as this within methodA.
  • It won't explode - it will just change the value of obj. Think of it as capturing the value of ExampleClass.this (so you can't change that) but you can change the data within the object referred to by ExampleClass.this.


  1. There are no "true" closures (functions that capture scope) in Java. See e.g.http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-different
  2. You can use this form to reference ambiguous methods / variables in the scope of "ExampleClass".
  3. You cannot change the reference. What you can do is use an indirection, e.g. a final reference to an object that can swap it's values. An example would be the class of Atomic value holders, e.g. AtomicReference.


  1. Because, the way you described it, in this case, they are not using ExampleClass.this.obj, they are calling the method ExampleClass.this.obj().

  2. ExampleClass.this refers to the encapsulating instance of ExampleClass in which this ClassA instance is instantiated.

  3. Not necessarily.

0

精彩评论

暂无评论...
验证码 换一张
取 消