14.07.2013 Views

Contents - Cultural View

Contents - Cultural View

Contents - Cultural View

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

final (Java) 120<br />

final (Java)<br />

In the Java programming language, the final keyword is used in several different contexts to define an entity which<br />

cannot later be changed.<br />

Final classes<br />

A final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the<br />

Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final<br />

class are implicitly final.<br />

Example:<br />

public final class MyFinalClass {...}<br />

Restricted subclassers are often referred to as "soft final" classes. [1]<br />

Final methods<br />

A final method cannot be overridden by subclasses. This is used to prevent unexpected behavior from a subclass<br />

altering a method that may be crucial to the function or consistency of the class. [2]<br />

Example:<br />

public class MyClass {<br />

}<br />

public final void myFinalMethod() {...}<br />

A common misconception is that declaring a class or method final improves efficiency by allowing the compiler to<br />

directly insert the method inline wherever it is called. This is not completely true; the compiler is unable to do this<br />

because the classes loaded at runtime might not be the same versions of the ones that were just compiled. Further,<br />

the runtime environment and JIT compiler have the information about exactly what classes have been loaded, and<br />

are able to make better decisions about when to inline, whether or not the method is final. [3]<br />

Final variables<br />

A final variable can only be assigned once. This assignment does not grant the variable immutable status. If the<br />

variable is a field of a class, it must be assigned in the constructor of its class. (Note: If the variable is a reference,<br />

this means that the variable cannot be re-bound to reference another object. But the object that it references is still<br />

mutable, if it was originally mutable.)<br />

Unlike the value of a constant, the value of a final variable is not necessarily known at compile time.<br />

Example:<br />

public class Sphere {<br />

public static final double PI = 3.141592653589793; // this is<br />

essentially a constant<br />

public final double radius;<br />

public final double xpos;<br />

public final double ypos;<br />

public final double zpos;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!