Final keyword in Java language is used with variables, methods and classes. The general idea behind the use of final is to restrict the manipulation of original value.
- Variables – The initial value can not be changed once it is assigned. You can initialize the final variable first time, but later it is not allowed to be modified.
- Method – It can not be overridden in the child classes
- Class – This class can not be extended with another child class.
Final Classes
Final classes can not be subclassed. If you declare a class with final keyword, then it implies that specified class can not be extended by another classes. This helps in restricting your class to be extended by any other classes. In Java API, java.lang.System and java.lang.String are final. Many other libraries also declared as final for the better use.
Final Methods
If a method is declared as final, then it can not be overridden by its subclasses. It is very much similar to declaring a method as private.
Final Variables
If a variable is declared as final, the values can not be modified once it is assigned. This is very useful if you want to prevent the manipulation of values in the future flow of your application. If a final variable is not initialized at the time of declaration, it is called as blank final variable. This has to be initialized in every constructor of the class. The best practice to declare final constants in the upper case letters.
Final Keyword Example
package javabeat.net.core; //Declare class as final public final class Employee { //Blank final variable without initialization private final String EMP_ID; //Initialize blank final variables in each constructor public Employee() { EMP_ID = "000"; } public Employee(String empId) { EMP_ID = empId; } //Declare method as final public final void getEmpId() { System.out.println(EMP_ID); } }
Modifying Reference
There is a confusion while using the final keyword with reference variables and modifying the actual content for the variable. Final prevents any modification on the reference variables by assigning with new references. But, it is allowed to modify the actual content of the reference. Look at the below example.
import java.util.ArrayList; import java.util.List; class Employee { private final List employees; public Test() { employees = new ArrayList(); employees.add("Employee1"); // Modification - This is perfectly allowed } public void setFoo(List employees) { //this.foo = foo; //compile time error. - This is not allowed } }