final is a non-access modifier applicable only to a variable, a method or a class.
Final variables
When a variable is declared with final keyword, its value can’t be modified, essentially, a constant. This also means that you must initialize a final variable. If the final variable is a reference, this means that the variable cannot be re-bound to reference another object, but internal state of the object pointed by that reference variable can be changed i.e. you can add or remove elements from final array or final collection. It is good practice to represent final variables in all uppercase, using underscore to separate words.
Initializing a final variable
- You can initialize a final variable when it is declared.This approach is the most common. A final variable is called blank final variable,if it is not initialized while declaration. Below are the two ways to initialize a blank final variable.
- A blank final variable can be initialized inside instance-initializer block or inside constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise compile time error will be thrown.
- A blank final static variable can be initialized inside static block.
Final classes
When a class is declared with final keyword, it is called a final class. A final class cannot be extended(inherited). There are two uses of a final class :
- One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper Classes like Integer,Float etc. are final classes. We can not extend them.
- The other use of final with classes is to create an immutable class like the predefined String class.You can not make a class immutable without making it final.