DRAFT
PrivateMeansFinal
Misconception:
The private
modifier protects a field from being changed.
Incorrect
A private field cannot be changed
Correct
Even a private field can be mutable
CorrectionHere is what's right.
Here is what's right.
Accessibility (private
) and changability (final
) are two orthogonal concepts. private
means that code in other classes cannot access (read or write) that field. final
means that the field cannot be changed (written) after initialization.
So, the following code works (the code in method m
can modify the field f
):
class A {
private int f;
A() {
f = 19;
}
void m() {
this.f = 9;
}
}
And this works, too (method m
can even modify field f
in another object of class A
):
class A {
private int f;
A() {
f = 19;
}
void m(A a) {
a.f = 9;
}
}
Language
Java