Reputation: 4569
Is there an equivalent in Java to the passing on const references in C++?
Isn't leaving out the "constness" misleading in regard to the method signature?
Upvotes: 12
Views: 9438
Reputation: 533500
BTW: Java does have const as a keyword, but you cannot use it anywhere.
Upvotes: 6
Reputation: 7942
As above,no there is no const in Java. But when we want to achieve 'close' to the same result in Java we use
public static final Object x = somedata;
This sets the data at that point and baring the abstraction leaks and so forth, you have as close to an equivalent as you can get.
Upvotes: 1
Reputation: 10603
The closest Java equivalent for const
is final
.
void func(final SomeClass x) {
// The following causes a compiler error
x = ...;
// The following works. If you don't want it to, then you have to make
// somevar final or write a getter (but not a setter) for it in SomeClass.
x.somevar = ...;
}
Upvotes: 0
Reputation: 6231
No, there isn't.
Java "final" is not an exact equivalent of C++ "const". The following (delayed initialization of a final variable) works in Java:
final double x;
int w = 1;
if (w > 2)
{
x = 0.5;
}
else
{
x = - 0.5;
}
but it doesn't work in C++ with "final" replaced by "const".
Using "final" on a variable in the method declaration can be useful in Java, because allows you to use this variable inside any anonymous class created inside your method.
PS. I was first disappointed by the lack of "const" in Java but later learned to live with "final".
PS2. The Java glossary (http://mindprod.com/jgloss/immutable.html) linked to in this thread has one thing wrong: no, you are not given a 100% guaranntee that the final variable doesn't change its value:
1) it changes from "undefined" to "defined", but the compiler will tell you if you reference it before initialization
2) on Linux, a double has 80-bit precision when stored in a register, but 64-bit when stored in memory. When a final double variable is pushed out of the register, it will be truncated and change its value. As Joel Spolsky says, "abstraction has sprung a leak".
Upvotes: 15
Reputation: 1500485
Java doesn't have anything like C++'s notion of const. It's a point of some contention, although it's interesting to note that .NET doesn't either. I believe the reasons are:
Upvotes: 8