wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes problem about anonymous inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "problem about anonymous inner class " Watch "problem about anonymous inner class " New topic
Author

problem about anonymous inner class

Peng Fan
Ranch Hand

Joined: May 04, 2004
Posts: 35
check out the following code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Wrapping{
public AnInterface aMethod(final int args){
return new AnInterface(){
private int i;
i = args
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
why should we declare the aMethod's argument as final, from the OO standpoint, what does the JVM benefit from doing such way?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Your code does not compile for several reasons. Do you mean something like this:

If you take the final out the compiler complains. It is a requirement that args is frozen so that the state of the object returned by aMethod() cannot be changed in unpredictable ways by external influences. The created object is only seeing a "snapshot" of the state of the local variables in the method invocation that creates it.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Peng Fan
Ranch Hand

Joined: May 04, 2004
Posts: 35
first i must say thank you for the wonderful illustration and sorry for my poor coding which is due to carelessness. i would feel more easy if you could give some examples of the external influences that affect the state of the object returned by the aMethod() and whether your principle could also explain the reason why local inner class enclosed by a method can only have access to the final variables defined in the enclosing method.
bas duijzings
Ranch Hand

Joined: Apr 07, 2004
Posts: 83
i hope you are studying for an exam. Otherwise i would suggest to redesign and not use inner classes. It has nothing to do with the fact that it does not work, but more with pure readability and maintenance.
It is generally better to make your code readeable.


have a nice one
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Here's an example where a referenced local variable disappears:

[ May 08, 2004: Message edited by: Barry Gaunt ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: problem about anonymous inner class
 
Similar Threads
Local Inner Classes
Interface questions
public modifier
Interface and Abstract Classes
Interface