- How to use final in Java? Final class, final method, and final variables Example
- What is the final modifier in Java? Example
- What is a blank final variable in Java?
- How to use final class in Java
- How to use a final variable in Java? Example
- How to use the final method in Java? Example
- Final Keyword In Java – Final variable, Method and Class
- 1) final variable
- Blank final variable
- Uninitialized static final variable
- 2) final method
- 3) final class
- Recommended Posts
- Top Related Articles:
- About the Author
- Comments
How to use final in Java? Final class, final method, and final variables Example
You can use the final keyword with variables, methods, and classes in Java. You can use the final modifier with variables to make them constant. A final variable is initialized only once in its lifetime, once initialized you cannot change its value. Though you can initialize the final variable at the time you declare them or you can initialize them at constructor if they are blank final variables. A static final variable, also known as a constant must be initialized in the same line. You can also use the final modifier with methods to prevent method overriding. In Java, you cannot override final methods.
This is usually done to signal that method is complete and it’s not designed for extension. It is also done to prevent someone deliberately or accidentally changing the core logic of the method by overriding it e.g. in template design pattern, the method which keeps the algorithm, also known as the template method should be final because the outline of the algorithm should be changed by the child classes.
You can also use the final keyword with classes to make sure they are not extensible. In Java, you can not extend a final class to create sub-classes. Why you make a class final? doesn’t it take your right of code reuse via Inheritance and extending its functionality? This is usually done to protect the class’s invariant due to security reasons.
This is why String is also made final in Java. If you are a beginner, just started learning Java, I suggest you refer at least one book alongside your research and practice. That will make you progress more in less time.
One of the good Java books for the beginner is Cay. S. Horstmann’s Core Java Volume 1 and 2, which is both readable, easy to understand, and comprehensive enough to learn Java in deep.
What is the final modifier in Java? Example
The final keyword is also known as a final modifier in Java. You can use a final modifier with class, method, and variables in Java. Once created and initialized, you cannot reassign a final variable. This may look easy but it’s a subtle concept to understand.
For example, it’s clear when you create a final int variable and initialize it to 5, now you cannot change its value, but if you create a final reference variable and store reference of an ArrayList on it, what will happen? Can you change ArrayList or not? Can you add/remove elements on that ArrayList? If yes, then what is protected by final modifier?
Well, you make the reference variable final, which means that the reference variable cannot point to any other object, but you can still change collection by adding or removing elements. If you want to prevent that, consider creating an immutable ArrayList in Java. You can create a read-only List in Java by using java.util.Collections class.
You can also refer to Cay S. Horstmann’s classic Core Java Volume 1 — Fundamentals to learn more about different usage of final keywords in Java.
What is a blank final variable in Java?
A blank final variable is a kind of final variable that is not initialized in the line they are created, instead, they are initialized in the constructor. The tricky thing to remember is that, if you have multiple constructors in a class then you must make sure to initialize a blank final variable in every constructor otherwise the compiler will give an error.
This is different with static final variables, which are also known as a compile-time constant and must be initialized in the same line they are declared.
How to use final class in Java
You make a class final in Java to prevent it from being inherited. You cannot extend a final class in Java. It also means that you cannot override any of the final class’s methods too, not even on anonymous or inner class.
Here is an example of the final class in Java :
final class Father< public final void getSurname()< System.out.println(«Sorry son, you cannot change your surname»); > > class Son extends Father
If you compile these two classes, Father and Son then you will get the compile-time error «The Type Son cannot subclass the final class Father» as shown in the following screenshot from Eclipse IDE :
How to use a final variable in Java? Example
There are three kinds of final variable in Java, static final variable, which is also known as a compile-time constant, non-static final variable, which can be initialized during declaration or can be a blank final variable and third one, local final variable which is declared inside a method or a block.
Until Java 8, you cannot use a local variable in Anonymous class until its final, but from Java 8 onward you can even if it’s effectively final i.e. it’s only initialized once or it’s not modified after initialization.
/** * Simple Java program to demonstrate how to use * final variable in Java. * * @author Javin Paul */ public class HelloFinal < // static final variable public static final float PIE = 3.14f; // non static final variable public final int count = 10; public HelloFinal()< count = 11; > public static void main(String args[]) < PIE = 7.12f; > >
When you compile this program using the javac compiler or just run it in Eclipse, you will get the following error :
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field HelloFinal.PIE cannot be assigned at HelloFinal.main(HelloFinal.java:22)
because our code is trying to assign new values of final variables which are not allowed.
How to use the final method in Java? Example
You make a method final when you think it’s complete and no one should override it, but there are some restrictions on which method can be made final. For example, you cannot make an abstract method final in Java because the only way to use an abstract method is by overriding it. Here is an example of how to make a method final in Java :
class Father< public final void getSurname()< System.out.println("Sorry son, you cannot change your surname"); > > class Son extends Father < public final void getSurname()< System.out.println("I want new surname"); > >
When you compile these two classes you will get the compile-time error «Cannot override a final method from Father» because Son is trying to override the getSurname() method which is declared final in Father class, as shown in the following Eclipse screenshot.
If you are still wondering what is the real use of the final method? or when to make a method final in Java? I suggest you read my article on when to make a method final in Java. There I have explained things in more detail and a couple of examples.
That’s all about how to use the final keyword in Java. As you have learned, you can use the final keyword with variables, methods, and classes in Java. You can use a final keyword to make a variable constant so that no one can change its value once created. When you decide to make it a constant consider making it a static final variable. You can also use the final keyword with a method to prevent overriding.
A final method is assumed to be complete and states that it’s not designed for inheritance or extension, as opposed to an abstract method that is actually designed for inheritance. You can also use the final keyword with classes to prevent sub-classing. You cannot extend a final class, this is usually done due to security reasons e.g. String is final in Java to protect its invariant from erroneous sub-classing.
- 10 things Every developer should know about static keywords in Java? (article)
- How to use the transient keyword in Java? (example)
- The difference between this and super keyword in Java? (answer)
- How to use the volatile keyword in Java? (example)
- 10 thins Every Programmer Should know about Thread in Java. (article)
- What Every Java Developer should know about Package? (article)
Final Keyword In Java – Final variable, Method and Class
In this tutorial we will learn the usage of final keyword. The final keyword can be used for variables, methods and classes. We will cover following topics in detail.
1) final variable
2) final method
3) final class
1) final variable
final variables are nothing but constants. We cannot change the value of a final variable once it is initialized. Lets have a look at the below code:
class Demo < final int MAX_VALUE=99; void myMethod()< MAX_VALUE=101; >public static void main(String args[]) < Demo obj=new Demo(); obj.myMethod(); >>
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field Demo.MAX_VALUE cannot be assigned at beginnersbook.com.Demo.myMethod(Details.java:6) at beginnersbook.com.Demo.main(Details.java:10)
We got a compilation error in the above program because we tried to change the value of a final variable “MAX_VALUE”.
Note: It is considered as a good practice to have constant names in UPPER CASE(CAPS).
Blank final variable
A final variable that is not initialized at the time of declaration is known as blank final variable. We must initialize the blank final variable in constructor of the class otherwise it will throw a compilation error (Error: variable MAX_VALUE might not have been initialized).
This is how a blank final variable is used in a class:
class Demo < //Blank final variable final int MAX_VALUE; Demo()< //It must be initialized in constructor MAX_VALUE=100; >void myMethod() < System.out.println(MAX_VALUE); >public static void main(String args[]) < Demo obj=new Demo(); obj.myMethod(); >>
Whats the use of blank final variable?
Lets say we have a Student class which is having a field called Roll No. Since Roll No should not be changed once the student is registered, we can declare it as a final variable in a class but we cannot initialize roll no in advance for all the students(otherwise all students would be having same roll no). In such case we can declare roll no variable as blank final and we initialize this value during object creation like this:
class StudentData < //Blank final variable final int ROLL_NO; StudentData(int rnum)< //It must be initialized in constructor ROLL_NO=rnum; >void myMethod() < System.out.println("Roll no is:"+ROLL_NO); >public static void main(String args[]) < StudentData obj=new StudentData(1234); obj.myMethod(); >>
More about blank final variable at StackOverflow and Wiki.
Uninitialized static final variable
A static final variable that is not initialized during declaration can only be initialized in static block. Example:
class Example < //static blank final variable static final int ROLL_NO; static< ROLL_NO=1230; >public static void main(String args[]) < System.out.println(Example.ROLL_NO); >>
2) final method
A final method cannot be overridden. Which means even though a sub class can call the final method of parent class without any issues but it cannot override it.
class XYZ < final void demo()< System.out.println("XYZ Class Method"); >> class ABC extends XYZ < void demo()< System.out.println("ABC Class Method"); >public static void main(String args[]) < ABC obj= new ABC(); obj.demo(); >>
The above program would throw a compilation error, however we can use the parent class final method in sub class without any issues. Lets have a look at this code: This program would run fine as we are not overriding the final method. That shows that final methods are inherited but they are not eligible for overriding.
class XYZ < final void demo()< System.out.println("XYZ Class Method"); >> class ABC extends XYZ < public static void main(String args[])< ABC obj= new ABC(); obj.demo(); >>
3) final class
We cannot extend a final class. Consider the following example:
final class XYZ < >class ABC extends XYZ < void demo()< System.out.println("My Method"); >public static void main(String args[]) < ABC obj= new ABC(); obj.demo(); >>
The type ABC cannot subclass the final class XYZ
Points to Remember:
1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.
5) A final method cannot be overridden.
6) A final class not be inherited.
7) If method parameters are declared final then the value of these parameters cannot be changed.
8) It is a good practice to name final variable in all CAPS.
9) final, finally and finalize are three different terms. finally is used in exception handling and finalize is a method that is called by JVM during garbage collection.
Recommended Posts
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Comments
Is there a difference in declaring a class final or marking the class and methods final. I think that making the class final makes the methods as well but I’m not sure for any extra information that i have missed in your post.
Dude, if you want only one of the methods of a super class to be not overridden by subclass, you need to mark the method as abstract instead of marking the class as final (which makes it not inheritable). And if you want all the methods in a super class to be not overridden but be available for sub class to access), u need to use abstract keywords for all abstract methods.
i like your website because every topic is simply represent with an good and useful example, that why everything gonna be easier to understand…. please carry on.
final int MAX_VALUE=99;
void myMethod() MAX_VALUE=101;
> instance variables and local variables are different , MAX_VALUE=101; should be intialized, and prints output 101 , as there is no relation in MAX_VALUE=99; and MAX_VALUE=101;