In C++ a reference argument to a function allows the function to make the reference refer to something else:
int replacement = 23;
void changeNumberReference(int& reference) {
reference = replacement;
}
int main() {
int i = 1;
std::cout << "i=" << i << "\n"; // i = 1;
changeNumberReference(i);
std::cout << "i=" << i << "\n"; // i = 23;
}
Analogously, a constant reference argument to a function will throw a compile time error if we try to change the reference:
void changeNumberReference(const int& reference) {
reference = replacement; // compile-time error: assignment of read-only reference 'reference'
}
Now, with Java, the docs say that functions arguments of non-primitive types are references. Example from the official docs:
public void moveCircle(Circle circle, int deltaX, int deltaY) {
// code to move origin of circle to x+deltaX, y+deltaY
circle.setX(circle.getX() + deltaX);
circle.setY(circle.getY() + deltaY);
// code to assign a new reference to circle
circle = new Circle(0, 0);
}
Then circle is assigned a reference to a new Circle object with x = y = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change.
To me this doesn't look at all like C++ references. It doesn't resemble regular C++ references because you cannot make it refer to something else, and it doesn't resemble C++ const references because in Java, the code that would change (but really doesn't) the reference does not throw a compile-time error.
This is more similar in behavior to C++ pointers. You can use it to change the pointed objects values, but you cannot changes the pointer's value itself in a function. Also, as with C++ pointers (but not with C++ references), in Java you can pass "null" as value for such an argument.
So my question is: Why does Java use the notion of "reference"? Is it to be understood that they don't resemble C++ references? Or do they indeed really resemble C++ references and I'm missing something?