Final (Java)

This is an old revision of this page, as edited by Myncknm (talk | contribs) at 03:58, 3 October 2007 (use of final keyword on classes and methods is not for efficiency). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In the Java programming language, the final keyword is used in several different contexts to define an entity which cannot later be changed.


A final class cannot be subclassed. This is done for reasons of security or efficiency. Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final class are implicitly final.

Example:

public final class MyFinalClass {...}


A final method cannot be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.[1]

Example:

public class MyClass {
    public final void myFinalMethod() {...}
}


A common misconception is that declaring a class or method final improves efficiency by allowing the compiler to directly insert the method inline where ever it is called. This is not completely true; the compiler is unable to do this because the classes loaded at runtime might not be same versions of the ones that were just compiled. Further, the runtime environment and JIT compiler have the information about exactly what classes have been loaded, and are able to make better decisions about when to inline, whether or not the method is final.[2]


A final variable is a constant. It can only be assigned a value once.

Example:

public class MyClass {
    public static final double PI = 3.141592653589793;
}