final Keyword in JAVA

The final Keyword

This section describes final classes, final methods, and final variables.

Final Classes

The Java programming language permits you to apply the keyword final to classes. If you do this, the class cannot be subclassed. For example, the class java.lang.String is a final class. This is done for security reasons, because it ensures that if a method references a string, it is a definite string of class String and not a string of a class that is a modified subclass of String that might have been changed.

Final Methods

You can also mark individual methods as final. Methods marked final cannot be overridden. For security reasons, you should make a method final if the method has an implementation that should not be changed and is critical to the consistent state of the object.

Methods declared final can be optimized. The compiler can generatecode that causes a direct call to the method, rather than the usual, virtual-method invocation that involves a runtime lookup. Methods marked as static or private can be optimized by the compiler as if they had been marked final, because dynamic binding cannot be applied in either case.

Final Variables

If a variable is marked as final, the effect is to make it a constant. Any attempt to change the value of a final variable causes a compiler error.

The following example shows a final variable that is defined properly:

public class Bank {

private static final double DEFAULT_INTEREST_RATE=3.2;

// more declarations


Note –
If you mark a variable of reference type (that is, any class type) as final, that variable cannot refer to any other object. However, you can change the object’s contents, because only the reference itself is final.

Blank Final Variables

A blank final variable is a final variable that is not initialized in its declaration. The initialization is delayed. A blank final instance variable must be assigned in a constructor, but it can be set once only. A blank final variable that is a local variable can be set at any time in the body of the method, but it can be set once only. The following code fragment is an example of how a blank final variable can be used in a class:

public class Customer {

private final long customerID;

public Customer() {

customerID = createID();


public long getID() {

return customerID;


private long createID() {

return … // generate new ID


… // more declarations


One thought on “final Keyword in JAVA

  1. Greetings from California! I’m bored at work so I decided to browse your blog on my iphone during lunch break. I enjoy the knowledge you provide here and can’t wait to take a look when I get home. I’m amazed at how quick your blog loaded on my cell phone .. I’m not even using WIFI, just 3G .. Anyways, awesome site!

Comments are closed.