Final (Java): Difference between revisions

Content deleted Content added
No edit summary
Line 3:
 
 
== Final classes ==
 
A '''final [[Class (computer science)|class]]''' cannot be [[Subclass (computer science)|subclassed]]. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final, for example {{Javadoc:SE|package=java.lang|java/lang|System}} and {{Javadoc:SE|package=java.lang|java/lang|String}}. All methods in a final class are implicitly final.
Line 12:
</source>
 
== Final methods ==
 
A '''final [[Method (computer science)|method]]''' cannot be [[Method overriding (programming)|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.[http://java.sun.com/docs/books/tutorial/java/IandI/final.html]
Line 25:
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 [[Just-in-time compilation|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[http://www.ibm.com/developerworks/java/library/j-jtp1029.html].
 
== Final variables ==
 
A '''final [[variable]]''' is [[Immutable object|immutable]]; it can only be assigned to once. If the variable is a field of a class, it must be assigned to 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.)