Final (Java)

This is an old revision of this page, as edited by Ezrarez (talk | contribs) at 17:56, 10 April 2006 (spelling). 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 done for reasons of efficiency, since the method can then be placed inline wherever it is called.

Example:

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

A final variable is a constant. It must be assigned a value at declaration, and the variable can later be used but not assigned a new value. Local variables (for example, variables in loops) cannot be declared final.

Example:

public class MyClass {
    public static final float PI = 3.1415;
}