i have a doubt regarding the initialization of class and instance variables. While we declare a variable as class variable(static variable) or an instance variable(member variable), it will be initialized to teh default initial value of the primitive type. For Eg: 0 for int. if we declare a variable, var as,
int var; and display this in a method, we will get the output as 0.
but, when we add the specifier, final, to the variable declaration, and execute the same code, it will give the compilation error as, "Teh blank final field var may not have been initialized"
My question is that why the compiler wont take the default value 0, as the value for that final constant?
if you put 'final' in front of one of your instance variables, you have to assign a value yourself. You can do this at the same time you declare that variable or you can do this in your constructors. However, you have to ensure that after your constructor (regardless of which one) has run, the variable will have a value assigned. Otherwise, the compiler will complain. If the compiler would set a default value at declaration time, you wouldn't be able to set a value in your constructors because of the 'final' modifier.
Despite the answers above to the contrary, there's certainly no logical reason for why this is so: it's just the way it is.
The language designers definitely could have chosen to let things work the way you describe, but the fact is that they did not, and so we'll just have to live with it.
To the three folks who tried to "explain" this above: it's really quite rare that you can logically explain any language feature. Although there may be rationales, ultimately it comes down to a person making a choice -- and more often than we'd like to admit, it's an arbitrary one.
To expand & clarify (or more likely obfuscate ) on what Thomas says:
You can assign a value to a final instance variable a) When the variable is declared OR b) in one (and only one) instance initializer block OR c) in all declared constructors, either directly in the constructor or indirectly by chaining.
This is a good example. However, this approach looks better when all the constructors serve each other towards the related functionality. In case of differ logic/functionality in each construtor, we will have to think again.
I understand this concept Ritchie. Once again thanks..
Joined: Oct 13, 2005
I am not quite sure what you mean about
In case of differ logic/functionality in each constructor, we will have to think again.
. . . but there should never be any difference in the logic of the constructors. Each constructor has one purpose and only one: to establish the invariants of the class for the first time.