Final (Java): Difference between revisions

Content deleted Content added
Typo corrected
m clean up
Line 1:
{{lowercase title}}
In the [[Java (programming language)|Java programming language]], the <code>'''final'''</code> [[Keyword (computing)|keyword]] is used in several contexts to define an entity that can only be assigned once.
 
Line 162:
</syntaxhighlight>
 
In addition, a blank final also has to be definitely assigned before being accessed. <ref name="define_assignment" />
<syntaxhighlight lang="java">
final boolean isEven;
Line 174:
</syntaxhighlight>
 
Note though that a non-final local variable also needs to be definitely assigned before being accessed. <ref name="define_assignment" />
 
<syntaxhighlight lang="java">
Line 188:
 
==C/C++ analog of final variables==
{{detailsfurther|const (computer programming)}}
In [[C (programming language)|C]] and [[C++]], the analogous construct is the <code>[[const (computer programming)|const]]</code> [[keyword (computer programming)|keyword]]. This differs substantially from <code>final</code> in Java, most basically in being a [[type qualifier]]: <code>const</code> is part of the ''[[data type|type]],'' not only part of the identifier (variable). This also means that the constancy of a value can be changed by casting (explicit type conversion), in this case known as "const casting". Nonetheless, casting away constness and then modifying the object results in [[undefined behavior]] if the object was originally declared <code>const</code>. Java's <code>final</code> is a strict rule such that it is impossible to compile code that directly breaks or bypasses the final restrictions. Using [[Reflection (computer programming)#Java|reflection]], however, it is often possible to still modify final variables. This feature is mostly made use of when [[Serialization|deserializing]] objects with final members.
 
Line 194:
 
==C# analogs for final keyword ==
C# can be considered as similar to Java, in terms of its language features and basic syntax: Java has JVM, C# has .Net Framework; Java has bytecode, C# has MSIL; Java has no pointers (real memory) support, C# is the same.
 
Regarding the final keyword, C# has two related keywords: