How to use Java final for classes, methods and variables

The keyword final is used in Java to create elements that cannot be changed. You can apply this modifier to classes, methods and variables. In particular, it is used to prevent errors and deliberate misuse within the code.

What is Java final?

Most programming languages allow existing code to be modified and expanded as desired. In Java, this is possible too, but there are instances when it’s crucial for an element to be designated as unchangeable. In Java, you can do this using the final modifier. This modifier is employed to limit access to a class, a method or a variable. Once a variable is declared as final, its value cannot be altered. A final class cannot be extended, and a final method cannot be overridden. This helps to safeguard against misuse of that section of code.

Web Hosting
Fast, scalable hosting for any website
  • 99.9% uptime
  • PHP 8.3 with JIT compiler
  • SSL, DDoS protection, and backups

Final classes

If you use Java final for a class, it can no longer be extended. This approach is very common, and in many cases, is used to prevent the derivation of a subclass. This applies to basic data types such as java.lang.Math or java.lang.String, which are always declared as final. Even if you want to prevent subclasses of a main class from being derived for other reasons, using Java final is the best way. In the following example, we’re going to create a final class and a second class that should theoretically extend it. After which, comes the main class with the main method.

final class FinalClass {
	public void exampleMethod() {
		System.out.println("This is a method within the final class.");
	}
}
class AdditionalClass extends FinalClass {
	public void exampleMethod() {
		System.out.println("The method is now also available in the additional class.");
	}
}
public class Main {
	public static void main(String[] args) {
		AdditionalClass ourAdditionalClass = new AdditionalClass();
		ourAdditionalClass.exampleMethod();
	}
}
java

The output you receive should look something like this:

Main.java:6: error: cannot inherit from final FinalClass
class AdditionalClass extends FinalClass
       ^
1 error
java

Final methods

If you mark a method as final, it cannot be overridden. This ensures that a method in a subclass cannot change its intended behavior. To achieve this, declare the method with the Java final modifier. For instance, consider a class named “Emperor” that includes a final method called “myTitle”. Another class, “King”, which extends “Emperor”, attempts to override the “myTitle” method. In the main method, we use an instance of “Prince” to access the method. The code appears as follows:

public class Emperor {
	public final void myTitle() {
		System.out.println("I am the emperor.");
	}
}
public class King extends Emperor {
	public final void myTitle() {
		System.out.println("I am the king.");
	}
}
public class Prince {
	public static void main(String[] args) {
		King myTitle = new King();
		King.myTitle();
	}
}
java

If you now apply this code, you will receive an error message:

Main.java:9: error myTitle() in King cannot override myTitle() in Emperor public final void myTitle() {
		^
overridden method is final
java

Final variables

Java final is also used to create variables with values that cannot be subsequently changed. This is particularly important if certain variables should remain constant within the code. In the following example, we’re going to create the variable x, which has the value 5. We’ll then try to insert this variable and assign it a new value. The code looks like this:

public class Main {
	final int x = 5;
public static void main(String[] args) {
	Main newValue = new Main();
	newValue.x = 10;
	System.out.println(newValue.x);
	}
}
java

When we use the Java command System.out.println to display the result, we receive the following error message:

Main.java:6: error: cannot assign a value to final variable x
	newValue.x = 10;
		     ^
1 error
java

Create empty final variables

Variables must always be initialized in Java. However, if you declare an empty final variable, you can initialize it with a class constructor. This is what the code looks like:

public class Example {
	final String exampleText;
	Example() {
		exampleText = "Here is your message.";
	}
	public static void main(String[] args) {
		Example newObject = new Example();
		System.out.println(newObject.exampleText);
	}
}
java

If you execute this code, you’ll receive the following sentence as output:

Here is your message.
java
Was this article helpful?
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.
Page top