We should initialize a final variable only once.
Its not a mandatory to initialize it at the time of declaration.Blank final variable in Java is a final variable which is not initialized while declaration, but we should initialize before using it.
There are three ways to do that for an instance variable.
1.By using constructor
2.By using instance initialization blocks.
3.At the time of declaration
Here is an example :
Here run the code only once when you call new finalVariable(...) and there is no way to call any of those again. This satisfies the requirement of the initialization happening only once per an instance.
Its not a mandatory to initialize it at the time of declaration.Blank final variable in Java is a final variable which is not initialized while declaration, but we should initialize before using it.
There are three ways to do that for an instance variable.
1.By using constructor
2.By using instance initialization blocks.
3.At the time of declaration
Here is an example :
public class finalVariable { private final int X; private final int Y; private final int Z = 10; { Y = 20; } public X(final int value) { X = value; } }
Here run the code only once when you call new finalVariable(...) and there is no way to call any of those again. This satisfies the requirement of the initialization happening only once per an instance.
No comments:
Post a Comment