• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static final variables..

 
edi kapllani
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

can you help me explaining why :
static final and final member variables need to be initialized explicitly at the declaration line (even not used in code);
thanks!
ciao!
------------------
edi
 
James Swan
Ranch Hand
Posts: 403
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
declaring a variable as final means its value cannot be changed, and its value can only be set where it was declared.
eg.
final int myVar = 5;
// the following will not work
myVar = 6;
Also, declaring a class as final means it can't be extended (sub-classed).
Declaring a method as final means that method can't be overwritten (assuming the class that defines the method is not already final).
James.
 
Bosun Bello
Ranch Hand
Posts: 1511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because it belongs to the class as a whole, and it can not be modified once a value is assigned. Since you can have a class without any objects being created, the only way the JVM can assure that static final values will have a value, is to make sure they are initialized at declaration time. final variables (non-static) are allowed to be initialized in the constructor(s).

Bosun
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic