This article will describe the following aspects of java’s “final” keyword:
- What is final keyword in Java
- final variables in Java
- final Methods in Java
- final Classes in Java
So, let’s begin!
What is final keyword in Java
It is a keyword that can be used with java classes, methods, and class attributes/variables. In java, the use of the final keyword makes the classes, variables, and methods non-changeable.
final variables in Java
If a variable is declared/created as final it means the value of that variable can’t be changed/modified. A final variable that is uninitialized can be initialized only using the java constructors.
In this example, we will declare a variable as final, and we will try to modify the value of such variable:
In the main method, firstly, we created the object of “FinalExample” class and afterward, we tried to modify the variable value using the class’s object:
The output showed that we encountered a compile-time error.
final Methods in Java
If we utilize the final keyword with a java method, it can’t be overridden.
In this example we will create a method “display()” using the final keyword:
- We created two classes: “PersonClass” and “EmployeeClass”.
- The “PersonClass” has a method named “display()”.
- The “EmployeeClass” inherits the “PersonClass”
- Within “EmployeeClass” we tried to override the “display()” method of “PersonClass”:
The error proved that the final method couldn’t be overridden in java.
final Classes in Java
In Java, we can’t create an (outer class) class as private or protected because java is an object-oriented language, and declaring a class as private or protected means restricting the classes to be inherited. So, java doesn’t allow private or protected classes. However, if someone doesn’t want to make a class inheritable, then what to do?
How to stop a class from being inherited in java?
To solve this problem, the final keyword can be utilized with the java classes. In java, any class declared/created with a final keyword wouldn’t be available for the inheritance.
In this example, we will create a PersonClass with the final keyword and we will try to inherit it from some other class:
In the above code snippet:
- We created two classes: PersonClass, and EmployeeClass.
- PersonClass is declared as final.
- EmployeeClass tried to extend the PersonClass.
The above snippet verified that a compile-time error occurred when we tried to access the PersonClass.
In java, a final keyword can be used with a variable, class, or method. The purpose of the final keyword is to restrict the usage of the java variables, classes, and methods. It restricts/stops the users from modifying the value of the variables, overriding the methods, and inheriting the classes. This post presented an in-depth overview of java’s final keyword with suitable examples.