final (Java)

This is an old revision of this page, as edited by 128.84.125.160 (talk) at 15:19, 14 October 2012 (Undid revision 517750581 by 128.84.125.160 (talk) forgot to log in). 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.

Final classes

A final class cannot be subclassed. This is done for reasons of security and 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 {...}

public class ThisIsWrong extends MyFinalClass {...} // forbidden

Restricted subclasses are often referred to as "soft final" classes.[1]

Final methods

A final method can't 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 {
    public void myMethod() {...}
    public final void myFinalMethod() {...}
}

public class AnotherClass  extends MyClass {
    public void myMethod() {...}            // Ok
    public final void myFinalMethod() {...} // forbidden  
}

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. In fact the compiler is unable to do this because the method is loaded at runtime and might not be the same version as the one that was just compiled. Only the runtime environment and JIT compiler have the information about exactly which classes have been loaded, and are able to make better decisions about when to inline, whether or not the method is final.[3]

Final variables

A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases. [4] (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 {

    // pi is a universal constant, about as constant as anything can be.
    public static final double PI = 3.141592653589793;  

    public final double radius;
    public final double xpos;
    public final double ypos;
    public final double zpos;

    Sphere(double x, double y, double z, double r) {
         radius = r;
         xpos = x;
         ypos = y;
         zpos = z;
    }

    [...]
}

Any attempt to reassign radius, xpos, ypos, or zpos will meet with a compile error. In fact, even if the constructor doesn't set a final variable, attempting to set it outside the constructor will result in a compilation error.

To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a single one:

    public final Position pos;

where pos is an object with three properties pos.x, pos.y and pos.z. Then pos cannot be assigned to, but the three properties can, unless they are final themselves.

Like full immutability, finality of variables has great advantages, especially in optimization. For instance, Sphere will probably have a function returning its volume; knowing that its radius is constant allows us to memoize the computed volume. If we have relatively few Spheres and we need their volumes very often, the performance gain might be substantial. Making the radius of a Sphere final informs developers and compilers that this sort of optimization is possible in all code that uses Spheres.

Blank final

The blank final, which was introduced in Java 1.1, is a final variable whose declaration lacks an initializer. [5][6] A blank final can only be assigned once and 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 occurs.[7]

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. However it is a misconception to think a final variable can itself not change, you simply cannot assign it more than once. For example, the following is a legal statement:

for (final SomeObject obj : someList) {
   // do something with obj
}

Since obj is only actually assigned in a single statement, it is legal even though obj will change with each iteration. [8]

Difference from the C++ const type qualifier

A final variable in Java means that variable can't be reassigned after initialization. C++ const can be used in this way (SomeClass * const ptr). The more common use SomeClass const * ptr means that the data being referenced can't be modified, although the reference itself can be changed to refer to different data. Both usages of C++ const can be combined (SomeClass const * const ptr).

Java's final is a hard rule. If you have a final variable, you cannot reassign it.

References

  1. ^ "How to Use the Eclipse API". The Eclipse Foundation. 2010. Retrieved 23 July 2010.
  2. ^ Writing Final Classes and Methods
  3. ^ Java theory and practice: Is that your final answer?
  4. ^ Java Language Specification #8.3.1.2.
  5. ^ Flanagan, David (May 1997). "Chapter 5 Inner Classes and Other New Language Features:5.6 Other New Features of Java 1.1". Java in a Nutshell (2nd Edition ed.). O'Reilly. ISBN 1-56592-262-X. {{cite book}}: |edition= has extra text (help)
  6. ^ "Types, Values, and Variables". Java Language Specification Chapter 4. Sun Microsystems, Inc. 2000. Retrieved 23 July 2010.
  7. ^ "Definite Assignment". Java Language Specification. Sun Microsystems, Inc. 2000. Retrieved 23 July 2010.
  8. ^ Pattis, Richard E. "More Java". Advanced Programming/Practicum 15-200. School of Computer Science Carnegie Mellon University. Retrieved 23 July 2010.