Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem about anonymous inner class

 
Peng Fan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peng Fan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's an example where a referenced local variable disappears:

[ May 08, 2004: Message edited by: Barry Gaunt ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic