final (Java)From Wikipedia, the free encyclopedia
In the Java programming language, the
[edit] Final classesA final class
cannot be extended. This is done for reasons of security and
efficiency. Accordingly, many of the Java standard library classes are
final, for example Example: public final class MyFinalClass {...} Restricted subclasses are often referred to as "soft final" classes.[1] [edit] Final methodsA 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.[2] Example: public class MyClass { A common misconception is that declaring a class or method final improves efficiency by allowing the compiler to directly insert the method inline wherever it is called. This is not completely true; the compiler is unable to do this because the classes loaded at runtime might not be the 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.[3] [edit] Final variablesA final variable can only be assigned once. This assignment does not grant the variable immutable status. If the variable is a field of a class, it must be assigned in the constructor of its class. (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.) Unlike the value of a constant, the value of a final variable is not necessarily known at compile time. Example: public class Sphere { Any attempt to reassign To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a single one: public final Position pos; where Like full immutability, finality of variables has great advantages, especially in optimization. For instance, [edit] Blank finalThe blank final, which was introduced in Java 1.1, is a final variable whose declaration lacks an initializer. [4][5] A blank final can only be assigned once and it must be unassigned when an assignment occurs. In order to do this, a Java compiler runs a flow analysis to ensure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment; otherwise a compile-time error must occur.[6] In general, a Java compiler will ensure that the blank final is not used until it is assigned a value and that once assigned a value, the now final variable cannot be reassigned another value.[7] |
|