Final keyword
A simple tutorial on the basics of java “final” keyword. This is very useful for java learners.
The final keyword is used to declare the final classes, final methods and final variables.
final class:
If the class is declared as a final, you can not extend this class. The purpose of this, nobody can change your functionality with overriding the methods.
We can avoid the sub-classing using final keyword. You can avoid the sub-classing using private constructor also, but you can not create the Instance out-side of that class.
Declaring the final class:
public final classname{
}
There are some final classes in the Java also. Some of them are:
String
StringBuilder
Integer
final method:
If the method is declared as final, you can not override this method. The purpose of this, if you extend the class also you can not override the final methods.
Declaring the final methods:
Public final return-type methodname() {
}
final variable:
If the variable is declared as final, you can not change the value of that variable. Whenever you need the constant values like pie, you can use the final variables.
Declaring the final variable:
public final float pie = 3.44f;
The pie variable value is constant, because of it's final variable. We can not change the value of pie variable once it is initialized.