• Post Reply Bookmark Topic Watch Topic
  • New Topic

final variable  RSS feed

 
Andrei Mura
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody explain me why the reference variable "tabsPane" must be declared final?

 
Campbell Ritchie
Sheriff
Posts: 53774
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch I have edited your post by adding code tags, an you can see how much better it looks.

Most probably because you have an anonymous class, which creates an object, and that object might be in existence after the method/constructor completes. So the object needs a copy of that reference. So it copies it. But what if the value of that reference changes before the method completes? Then there will be two different copies of the same thing. That would be disastrous. A compiler cannot check that there have been no changes to the value of the local variable (or parameter) in the method (it is too complicated) but it can check that it is declared final, so it can't be changed.

I suspect you want to use the tabPane field in the anonymous class. The rule about "final" doesn't apply to fields because fields are still in existence after the method complete.
 
Andrei Mura
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Richie. Your explanation helped me v. much. Tx!!
 
Campbell Ritchie
Sheriff
Posts: 53774
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!