Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use final keyword with anonymous inner classes?

Tags:

I'm currently preparing the S(O)CJP, with the Sierra & Bates book.

About inner classes (method local or anonymous), they say that we can't access the local variables because they live on the stack while the class lives on the heap and could get returned by the method and then try to have access to these variables that are on the stack but do not exist anymore since the method has ended...

As we all know, we can bypass this by using the final keyword. This is what they say in the book but they don't really explain what's the effect of that final keyword... As far as i know, using the final keyword on a method local variable doesn't make it live on the heap... So how would the class be able to access a final variable that still lives on the stack while there could be no more stack???

I guess there should be some kind of "copy" of this final local variable inside the inner class. Since the value can't change, why not duplicating this information... Can someone confirm this or tell me if i'm missing something?

like image 651
Sebastien Lorber Avatar asked Aug 16 '11 10:08

Sebastien Lorber


People also ask

What is the use of anonymous inner class?

An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class. Tip: Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphics programming.

Why do we use final keyword?

The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override). The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...). The final keyword is called a "modifier".

Why would you use an anonymous class rather than an inner class?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

When Should anonymous inner classes be used?

In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways: Class (may be abstract or concrete).


1 Answers

Your intuition is correct, because the variable is final it is safe to make a copy of it. Of course for reference types this means copying the reference to the object and not the object it refers to.

like image 115
brain Avatar answered Oct 19 '22 07:10

brain