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 variable, method and class in Java

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 :

Can we make a class final in Java?


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.

Final class, method and variable example in Java


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.


Recommended articles for further learning :
  • 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)

2 comments:

  1. Nice guide of final modier in Java. Thanks, but I have one question? is there any change in behavior of final variable across Java version or they are exactly same from Java 1 to Java 8?

    ReplyDelete
    Replies
    1. @Anonymous, behavior of final modifier is not changed since first Java release. Though a new concept called effectively final is introduced in Java 8, in relation to using local final variable inside anonymous class or lambda expression. See this tutorial to learn more about effectively final in Java 8.

      Delete

Feel free to comment, ask questions if you have any doubt.