This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why is implicit initialization of class final fields (static and nonstatic) not allowed?

 
Alexander Shrago
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My jre 1.6 compiler generate an error in case of final field (static and nonstatic) may not be initializated. It doesn't even depends on if this field is used.
It is strange because class fields (static and nonstatic but not final) may be implict initialized during declaration.
And it's strange because the compiler requires the initialization of final local variables only in case of their usage.

I want to understand the logic of it to prepare to SCJP exam ...
 
Achilleas Achix
Ranch Hand
Posts: 123
BSD Java Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


mine complains only about final static.
 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Achilleas Achix wrote:mine complains only about final static.

And if you remove that error then it will complain about the instance final variable. Alexander, what is the use of a constant if you don't initialize it? Even if you want your final variable to have a value of 0, your code must have that assignment otherwise the whats the purpose of that final variable. As for the compiler error, once a final variable of a class (static or non-static) is not initialized, there is no way for the compiler to be able to check where it is used as there are many possible ways in which you can access the value of the variable. This is why the compiler forces you to initialize it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic