This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Understanding Final

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


What I think is final instance variable get their default values if not initialized
class Finale
{ final int x;
final String s;
public static void main(String args[])
{
System.out.println(new Finale().x);
System.out.println(new Finale().s);
}
}

compiler says x might not have been initialized
So does that mean final instance variable don`t get their default values.

and the other one is

class Cant_Initialize
{
final int x;
public static void main(String args[])
{
Cant_Initialize c=new Cant_Initialize();
c.x=10;
}
}

Now compiler says can`t assign value to a final variable

so does it means that final instance variable have to be initialized when they are declared

class Constant
{
final int x=10;
}

Last one , final without static .So does it mean that every instance of class Constant will have its own final int x variable.
And since it makes no sense that each instance to have a final variable so we make it static
 
Himai Minh
Ranch Hand
Posts: 1142
4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Mahtab,
Answers to your 3 questions:
1. final variable means a contant variable. The compiler won't initialize it for you because it does not know what constant value you will assign to the final variable. If the compiler set x =0 at the beginning, what if you change x to 10 later?
For this reason, the compiler sets a rule that final variable should be initialized in the declaration or in the constructor.

2. In Cant_Initialize, final variable should be assigned a value in a contructor or declaration.This can prevent programmer to re-assign values to the constant variable.

3. Yes. Each instance has its own constant variable.
 
Douglas Mortimer
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to add, the third place you may assign a value to a final variable is in an initialization block (static or instance). Both execute before the class's constructor completes, which is what is required.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic