The Magic of Final Keyword in Java

In this post, we will discuss all things final in Java. Final Classes, Final Methods, Final Variables and finally Final Arguments.

Final Classes

Let us look at an example. We have a class A that is declared as final.

final class A {
}
view raw finalClass1.java hosted with ❤ by GitHub

Now let us try to create a subclass of A

final class A {
}
class B extends A { // This will give compilation error
}
view raw finalClass2.java hosted with ❤ by GitHub

This will give a compilation error. The reason is that a final class cannot be subclassed. Once you subclass, you can potentially modify the public methods of the parent class. By declaring the class as final, you as a developer ensure that no unwarranted effects take place with respect to your code.

Some popular classes in the Java library that are declared as final are String, Integer, Boolean.

Final Methods

class ABC {
public void method() {
}
}
class B extends ABC {
@Override
public void method() {
}
}
view raw finalMethods.java hosted with ❤ by GitHub

Now if we make the method in the super class as final

class ABC {
final public void method() {
}
}
class B extends ABC {
@Override
public void method() { // This will give compilation error
}
}
view raw finalMethod2.java hosted with ❤ by GitHub

This gives a compilation error. The final method cannot be overridden.

Final Variables

public class Final {
public static void main(String args[]) {
int i = 5;
i = 7;
}
}
view raw finalVariable1.java hosted with ❤ by GitHub

You can assign the value to a variable any number of times. However, when you declare the variable as final, it can be assigned the value only once. If you try to assign a value to the variable a second time, it will throw a compilation error.

public class Final {
public static void main(String args[]) {
final int i = 5;
i = 7; // This will give compilation error
}
}
view raw finalVariable2.java hosted with ❤ by GitHub

The above will give a compilation error.

Final Arguments

public void somemethod(int arg) {
arg = 5;
}
view raw finalArg1.java hosted with ❤ by GitHub

Although not advisable, you can change the value of the argument in a function. However, when the argument is declared as a final, its value cannot be changed.

public void somemethod(final int arg) {
arg = 5; // This will give a compilation error
}
view raw finalArg2.java hosted with ❤ by GitHub

The above will give a compilation error

Summary:

Final classes cannot be subclassed. Final methods cannot be overridden. Final variables and final arguments cannot be assigned a value more than once.

Typically, java coding standards say that all variables and all arguments should be declared as final.