"Final" keyword

Josh - Jun 2 '21 - - Dev Community

In this post I am going to be reviewing the final keyword and how it is used in Java applications. The final keyword can be different depending on the context. When variables are declared using it they are locked to the value they are assigned.

final String string = "Hello World";
Enter fullscreen mode Exit fullscreen mode

A final variable can be declared but not initialized.

final String string;
Enter fullscreen mode Exit fullscreen mode

This allows for each object to then assign that constant variable with a value rather than locking in the same for all instances of the class. Class constants can be created by combining static with final. A useful example of this is if a Math class was created and the developer wanted to make pi a constant that can be called in every instance.

final static float PI = 3.14;
Enter fullscreen mode Exit fullscreen mode

Reference variables are similar in that once they have been assigned they cannot be reassigned. This does not mean the object is immutable however. The properties of the class can be updated and set using the available methods.

final Object object = new Object();
object.setName("NewName");  
Enter fullscreen mode Exit fullscreen mode

Methods with the final keyword are restricted to not being overridden. Classes that are extended but have methods that need to stay the same can make use of the final keyword. An example of this is the thread class’ isAlive() method. The class can’t be overridden and the compiler will throw and error if attempted. Lastly, the parameters of a method can also utilize the final keyword. The parameters marked with final are not changeable in the method from what they are assigned.

public void myMethod(final String string);
Enter fullscreen mode Exit fullscreen mode

Thank you to everyone that has read this post. If you learned something new please like or comment down below.

Sources:

  1. final keyword in java. GeeksforGeeks. (2021, February 17). https://www.geeksforgeeks.org/final-keyword-java/.

  2. Baeldung. (2020, May 3). The "final" Keyword in Java. Baeldung. https://www.baeldung.com/java-final.

. . . . . . . . . . . . . . . . . . . . .