Final (Java): Difference between revisions

Content deleted Content added
Adding local short description: "Keyword in the Java programming language", overriding Wikidata description "keyword from the Java programming language"
Line 190:
==C/C++ analog of final variables==
{{further|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.
 
Further, because C and C++ expose pointers and references directly, there is a distinction between whether the pointer itself is constant, and whether the data pointed to by the pointer is constant. Applying <code>const</code> to a pointer itself, as in <code>SomeClass * const ptr</code>, means that the contents being referenced can be modified, but the reference itself cannot (without casting). This usage results in behaviour which mimics the behaviour of a <code>final</code> variable reference in Java. By contrast, when applying const to the referenced data only, as in <code>const SomeClass * ptr</code>, the contents cannot be modified (without casting), but the reference itself can. Both the reference and the contents being referenced can be declared as <code>const</code>.
 
In C++, the <code>final</code> keyword is used to denote that a function cannot be further overridden. It is also used similarly to Java to declare a class as final (cannot be extended), like {{code|class Z final: public X, public Y {}|cpp}}
 
==C# analogs for final keyword ==