'final' is used for defining constants. Constants always have pre-determined specific values. No point in having a constant with a default value which you do not know unless you open language manuals. So we agree that a final variable(so to say) must be explicitly initialized.
This is in contrast with non-final member variables where explicit initialization is not required. Don't forget that a variable must be initialized before use. Non final member variables are by default initialized. Local varibales are not default-initialized.

So we have to find a way to ensure that our final varibales are always explicitly initialized before use.

Instance final variables -
This can be done in constructors, instance blocks or inline. This ensures that the variable always initailized before use.

Class final variables -
These are not owned by instances. So there is no way you can ensure that these are initialized before use except it initializing it inline or thru static block.

Local final variables -
Only one way, assign a value before use. Not very different from non-final local variables except that the former is a constant.

No comments:

Post a Comment