Think about it logically... a final means that once the variable is set, it cannot change. It's constant for the life of the object. So what would happen in the following code if we waited to initialize the value of a final variable?
Trace through the code. What would happen to "SOME_CONSTANT" if this were legal? Would its value be final?
Now compare that to this:
Trace through the code. Now the value of the final is truly final. Why?
Remember, for specific instance of an object, the constructor can only be called once.
Make sense? [ August 10, 2008: Message edited by: Mark Vedder ]
I also saw this in the SCJP6 Study Guide. Any idea why it doesn't say "final reference variables must be initialized before the constructor completes"? (in the context of instance variables)
Afaik, final primitive instance variables also need to be initialized before the constructor completes...
Wout Er wrote:Afaik, final primitive instance variables also need to be initialized before the constructor completes...
Actually, if you don't initialize them, I think they will be given a default value (eg, 0) - but I wouldn't stake my life on it. What you can't do is set them anywhere outside the constructor or in place.
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Winston Gutkowski wrote:Actually, if you don't initialize them, I think they will be given a default value (eg, 0) - but I wouldn't stake my life on it.
Only non-final member variables are initialized to default values when you don't initialize them explicitly. Final member variables must be explicitly initialized - if you don't, the compiler will complain.
As far as I know there is no difference between variables of primitive and non-primitive types with regard to this.