• 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

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi!
If I have a final instance variable it seems I must declare it either right away e.g. "public final int i = 5" or in the constructor. Why? And why doesn't it get a default value like a non final variable would??
//Cecilia
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Cecilia,
JLS 8.3.1.2 gives the answer:


8.3.1.2 final Fields
A field can be declared final (�4.5.4). Both class and instance variables (static and non-static fields) may be declared final.
It is a compile-time error if a blank final (�4.5.4) class variable is not definitely assigned (�16.7) by a static initializer (�8.7) of the class in which it is declared.
A blank final instance variable must be definitely assigned (�16.8) at the end of every constructor (�8.8) of the class in which it is declared; otherwise a compile-time error occurs.


HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
[This message has been edited by Valentin Crettaz (edited November 25, 2001).]
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To add some additional "whys" to what is explained above - the whole purpose of a final field is so that it will be constant throughout its' lifetime. So you are not allowed to assign a value to it OTHER THAN when it is being created - that is, in its declaration, or in the constructor. As an example, you'd use it for something like PI, which you don't want any users to change if they were to extend your class, or for something like stateSalesTax.
 
Don't MAKE me come back there with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic