• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static Final Variable Confusion & its limitation in context of Constructor  RSS feed

 
Kr. Gaurav
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well i am very well aware of;

   
  • If we declare Blank Final variable that can be initialized either in Constructor or Instance Initializer Block( which, not considered as a good coding convention)

  •    
  • In same fashion we can also initialized or if already initialized then can change the value of Static variable inside the Constructor

  •    
  • Anyone can can access Static final variable i.e [system.out.print("any static final variable")]  inside the Constructor if already initialized while declaration.

  •    
  • Finally that we can initialized blank Static Final variable only inside the Static Initializer Block



  • I am well aware of the concepts like Constructor Creation / Static / Final and when all these allocated memory locations while application execution. So here is my confusion that Why i can't initialize value to blank static final variable already declared at class level, inside the Constructor ?


    I need an Crystal Clear explanation on the same any HELP will be deeply appreciated 
     
    Junilu Lacar
    Sheriff
    Posts: 11494
    180
    Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Because a static final variable must be initialized when the class is loaded into memory. Once the class has been loaded into memory and the static final variable initialized to some value, it can no longer be reassigned a different value. A constructor will only be executed when you instantiate the class, normally with new. The constructor is executed in the context of creating a new instance of the class and this is not a legal context in which a static final variable can be assigned a value.  You can only do that in the declaration of the variable, or in the case of a blank declaration that doesn't include an initialization, in a static initialization block.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!