What is final in Java? Final variable , Method and Class Example (original) (raw)
Final in Java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is a final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase the performance of Java application.
Example of Final variable, Final method, and Class in Java
Now, let's understand the final keyword in detail in Java. We will start with final variable then explore final methods and finally the final class in Java. After going through these examples, you will learn the impact of making a variable, method, or a class final in Java.
1. What is a final keyword in Java?
Final is a keyword or reserved word in Java and can be applied to member variables, methods, class and local variables in Java. Once you make a reference final you are not allowed to change that reference and compiler will verify this and raise a compilation error if you try to re-initialized final variables in Java.
2. What is the final variable in Java?
Any variable either a member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declared with static keyword in java and treated as constant. Here is an example of final variable in Java
public static final String LOAN = "loan";
LOAN = new String("loan") //invalid compilation error
Final variables are by default read-only.
3. What is the final method in Java?
The final keyword in Java can also be applied to methods. A Java method with the final keyword is called a final method and it can not be overridden in the subclass. You should make a method final in Java if you think it’s complete and its behavior should remain constant in sub-classes.
In general, final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded at compile-time, See these Java Performance courses for more details.
Here is an example of a final method in Java:
class PersonalLoan{
public final String getName(){
return "personal loan";
}
}
class CheapPersonalLoan extends PersonalLoan{
@Override
public final String getName(){
return "cheap personal loan"; //compilation error: overridden method is final
}
}
4. What is the final class in Java?
Java class with the final modifier is called the final class in Java. The final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer, and other wrapper classes. Here is an example of final class in java
final class PersonalLoan{
}
class CheapPersonalLoan extends PersonalLoan{ //compilation error: cannot inherit from final class
}
Benefits of final keyword in Java
Here are a few benefits or advantages of using the final keyword in Java:
1. Final keyword improves performance. Not just JVM can cache the final variables but also applications can cache frequently use final variables.
2. Final variables are safe to share in a multi-threading environment without additional synchronization overhead.
3. Final keyword allows JVM to an optimized method, variable or class.
Final and Immutable Class in Java
Final keyword helps to write an immutable class. Immutable classes are the one which can not be modified once it gets created and String is a primary example of an immutable and final class which I have discussed in detail on Why String is final or immutable in Java.
Immutable classes offer several benefits one of them is that they are effectively read-only and can be safely shared in between multiple threads without any synchronization overhead. You can not make a class immutable without making it final and hence final keyword is required to make a class immutable in Java.
Example of Final in Java
Java has several system classes in JDK which are final, some examples of final classes are String, Integer, Double, and other wrapper classes. You can also use a final keyword to make your code better whenever it is required. See the relevant section of the Java final tutorial for examples of the final variable, final method, and final class in Java.
Important points on the final modifier in Java
1. The final keyword can be applied to a member variable, local variable, method, or class in Java.
2. The final member variable must be initialized at the time of declaration or inside the constructor, failure to do so will result in a compilation error.
3. You can not reassign the value to a final variable in Java.
4. The local final variable must be initialized during declaration.
5. The only final variable is accessible inside an anonymous class in Java,, but in Java 8, there is something called effectively final variable, which is non-final local variables but accessible inside the anonymous class.
The only condition is that they should not be reassigned a value once created. If you do so, the compiler will throw an error. See Java SE 8 for Really Impatient for more details.
7. A final class can not be inheritable in Java.
9. Final should not be confused with finalize() method which is declared in Object class and called before an object is garbage collected by JVM.
10. All variables declared inside the Java interface are implicitly final.
11. Final and abstract are two opposite keywords and a final class can not be abstract in Java.
12. Final methods are bonded during compile time also called static binding.
13. Final variables which are not initialized during declaration are called a blank final variable and must be initialized in all constructors either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".
14. Making a class, method, or variable final in Java helps to improve performance because JVM gets an opportunity to make assumptions and optimization.
15. As per Java code convention, final variables are treated as constant and written in all Caps like
private final int COUNT=10;
16. Making a collection reference variable final means only reference can not be changed but you can add, remove or change object inside collection. For example:
private final List loans = new ArrayList();
loans.add(“home loan”); //valid
loans.add("personal loan"); //valid
loans = new Vector(); //not valid
That’s all on final in Java. We have seen what is final variable, the final method is, and the final class in Java and what do those mean. In Summary, whenever possible start using final in java it would result in better and faster code.
Java Tutorial you may like:
How to debug Java program in Eclipse
Thanks for reading this article so far, if you like this tutorial then please share it with your friends and colleagues. If you have any questions then please drop a comment.