• Post Reply Bookmark Topic Watch Topic
  • New Topic

final initialization  RSS feed

 
saravanan ragunathan
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


this code generates compilation error..
a might not have been initialized..
i think default constructor doesn't initialize
final variables...is this correct?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Language Specification says (paragraph 8.3.1.2 final Fields):
JLS wrote:
It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared.

Paragraph 4.12.4 final Variables to which this refers, says:
JLS wrote:
A variable can be declared final. A final variable may only be assigned to once. It is a compile time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.

A blank final is a final variable whose declaration lacks an initializer.

So, it says indeed that you must provide an initializer for final variables, otherwise you'll get a compiler error.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That includes explicitly initialising it in the constructor.
 
saravanan ragunathan
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i read that
blank fianl class variable must be assigned using static initializer
blank final instance variable must be assigned at the end of every constructor

why the java language designers taking this stufff why not just
assign them using default constructor(like instance variable and static variable)..

 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not quite.
A static final field must be initialised by a static initialiser, or immediately on declaration.
An instance final field must be initialised before every constructor (overloaded or otherwise) completes. Again initialisation immediately on declaration is permissible.
The idea behind a field is that it will not normally take the default values of 0/null/false. Since a final field can only be assigned to once, the compiler checks that it has been assigned a value at all, once and once only. Although in special cases the value wanted will be identical to the default values, it was decided to insist on an assignment.

This is an unusual example, in that the final field ought to have the value zero:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!