Content deleted Content added
m Bot: link syntax/spacing and minor changes |
|||
Line 17:
== Final methods ==
A '''final [[Method (computer science)|method]]''' cannot be [[Method overriding|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.<ref>[http://java.sun.com/docs/books/tutorial/java/IandI/final.html Writing Final Classes and Methods]</ref>
Example:
Line 37:
== Final variables ==
A '''final [[Variable (programming)|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.
Unlike the value of a [[constant (computer science)|constant]], the value of a final variable is not necessarily known at compile time. It is considered good practice to represent final [[
Example:
Line 78:
===Final and inner classes===
When an anonymous [[inner class]] is defined within the body of a method, all variables declared <code>final</code> in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the <code>final</code> variable cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its [[call stack|stack frame]] has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.
<source lang="Java">
Line 105:
===Blank final===
The '''blank final''', which was introduced in Java 1.1, is a final variable whose declaration lacks an initializer.
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>
Line 115:
</source>
Since obj is only actually assigned in a single statement, it is legal even though obj will change with each iteration.
==Difference from the C++ <code>const</code> type qualifier==
|