Home > Backend Development > C++ > body text

Java\'s `final` vs. C \'s `const`: How Do They Differ Beyond the Surface?

Susan Sarandon
Release: 2024-10-27 08:03:02
Original
144 people have browsed it

 Java's `final` vs. C  's `const`: How Do They Differ Beyond the Surface?

Java's 'final' vs. C 's 'const': The Nuances Beyond Similarity

While the Java for C programmers tutorial suggests that Java's 'final' keyword roughly equates to C 's 'const,' a closer examination reveals subtle differences.

Function Member Semantics

In C , marking a member function 'const' signifies that it can be invoked on 'const' instances. Java lacks this feature. For instance, in C , 'i.foo()' is permitted on 'const Foo& i,' but 'i.bar()' would be prohibited.

Value Assignment

In Java, final variables can be assigned once, but later. This is not allowed in C . For example, in Java, 'a = 10;' is legal in 'public class Foo { void bar() { final int a; } }.' However, in C , such assignment would be invalid.

Member Variables

Both Java and C allow member variables to be 'final' or 'const,' respectively. In Java, these variables must be set before the constructor completes, while in C , initialization lists must be used.

Override Prevention

Java's 'final' keyword can be used to prevent method overriding. C (pre-C 11) lacks this capability. In Java, 'public final void foo() {}' in the base class cannot be overridden in derived classes. However, in C (pre-C 11), overriding would be possible.

C 11 Update

C 11 introduced 'final' to provide semantics equivalent to Java's final. This allows marking classes and member functions as 'final,' preventing overriding. Additionally, 'final' can be combined with 'const' for member functions.

Conclusion

While Java's 'final' and C 's 'const' share similarities, subtle differences exist in how they apply to member function semantics, value assignment, member variables, and override prevention. C 11 expanded 'const' to include the concept of 'final,' providing greater alignment with Java in this aspect.

The above is the detailed content of Java\'s `final` vs. C \'s `const`: How Do They Differ Beyond the Surface?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!