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 void 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.
Example:
public class MyClass { public static final double PI = 3.141592653589793; }