In Java, the final keyword is used to define an entity that can only be assigned once. The final keyword can be used in multiple contexts:
- Final variable (Create constant variable)
- Final method (Prevent method overriding)
- Final class (Prevent inheritance)
Final variable
When a variable is declared with the final
keyword, it means the value cannot be changed once it is initialised (it is a constant). Final variable names are normally declared in all cpas.
Note
A final variable must be initialised when it is declared, in the constructor (for instance variables), or in a static block (for static variables).
Initialise upon declaration
100
Initialise in constructor
200
Initialise in static block Learn more about static block on Static block.
300
Final method
When a method is declared with the final
keyword, the method cannot be overridden by subclasses.
Compile Time Error
Final class
When a class is declared with the final
keyword, the class cannot be extended.
Note
Final methods from parent classes can be inherited, but they cannot be overridden.
Compile Time Error
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_DevelopmentProgramming_LanguagesJavaFinal_KeywordFinal_ClassFinal_MethodFinal_Variable
Reference: