Final (Java): Difference between revisions

Content deleted Content added
No edit summary
Undid revision 516113307 by 134.91.226.47 (talk)
Line 3:
 
== Final classes ==
 
A '''final [[Class (computer science)|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 {{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.
 
Example:
<source lang="java">
public final class MyFinalClass {...}
 
public class ThisIsWrong extends MyFinalClass {...} // forbidden
</source>
 
Restricted subclasses are often referred to as "soft final" classes.<ref>{{cite web|url=http://www.eclipse.org/articles/article.php?file=Article-API-Use/index.html|title=How to Use the Eclipse API|year=2010|publisher=The Eclipse Foundation.|accessdate=23 July 2010}}</ref>
 
== Final methods ==
Line 37 ⟶ 48:
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) {
Line 63 ⟶ 78:
===Blank final===
 
The '''blank final''', which was introduced in Java 1.1, is a final variable whose declaration lacks an initializer. <ref>{{cite book|last=Flanagan|first=David |title=Java in a Nutshell|url=http://web.deu.edu.tr/doc/oreily/java/javanut/ch05_06.htm|edition=2nd Edition|date=May 1997 |publisher=O'Reilly|isbn=1-56592-262-X|chapter=Chapter 5 Inner Classes and Other New Language Features:5.6 Other New Features of Java 1.1}}</ref><ref>{{cite web|url=http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html|title=Types, Values, and Variables|year=2000|work=Java Language Specification Chapter 4|publisher=Sun Microsystems, Inc|accessdate=23 July 2010}}</ref> 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.<ref>{{cite web|url=http://java.sun.com/docs/books/jls/second_edition/html/defAssign.doc.html|title=Definite Assignment|year=2000|work=Java Language Specification|publisher=Sun Microsystems, Inc.|accessdate=23 July 2010}}</ref>
 
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: <br>
<source lang="Java">
 
for (final SomeObject obj : someList) {
// do something with obj
}
</source>