Const (computer programming): Difference between revisions

Content deleted Content added
m sp fix
Final: more explanation
Line 172:
i = 4; // this results in compiler-time error.
 
It must be decidable by the compilers where the the variable with the <code>final</code> marker is initialised, and it must be performed only once, or the class will not compile. Unlike C++'s <code>const</code>, the Java <code>final</code> keyword only protects a variable from assignment, and does not guarentee its immutability. The keyword <code>final</code> can be given to a method definition in Java, but unlike in C++ its semantics are that the method cannot be overriden in subclasses. It is interesting to note that whereas Java's <code>final</code> and C++'s <code>const</code> keywords have the several meaning when applied with primitive variables, their meanings diverge when appended to method definitions. Java cannot simulate C++'s <code>const</code> methods, similarly C++ does not have an equivalent feature for Java's <code>final</code> modifier.
The variable with <code>final</code> must be initialized explicitly.
 
Interestingly, the Java language specification regards const as a reserved keyword, i.e. one that cannot be used as variable identifier, but assigns no semantics to it. It is sometimes thought that this reservation of the keyword occurred to allow for an extension of the Java language to include const methods.
Unlike C++, a method with <code>final</code> merely means that the method would not be overriden.
 
==Footnotes==