• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

final variables

 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Here is the question:
class FinalTest{
final int q;
final int w=0;
FinalTest(){
q=1;
}
FinalTest(int x){
q=x;
}
}
why does code compiles correctly without any
warnings or errors for the final variables
redeclare?
thanks
Krussi
 
Ranch Hand
Posts: 775
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
- Declaring and initializing variables are two separate activities.
- For non-final member variables, there is a default initialization.
- For final member variables, there is no default initialization.
- Initialization doesn't have to happen in the same statement as the declaration, it just has to happen by the time you've completed construction of the instance (in the case of final instance variables; for final static variables it would have to happen by the time you've finished executing all the initialization blocks for the class)
[ May 02, 2002: Message edited by: Reid M. Pinchback ]
 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

final variables
redeclare?
[/QB]


I think you mean reassign...
The compiler determines that there are no chance that the final variable q will ever be re-assigned, because neither constructor invokes the other. It means that each time an object is created, q will be initialized only once, either in the first or in the second constructor, never in both.
However, adding the this() call to any constructor will cause a compile error because there is a chance that q will be reassigned.
 
krussi rong
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks all of you!
Krussi
 
Please do not shoot the fish in this barrel. But you can shoot at this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic