class WithPrivateFinalField {
private final String s = \"I’m totally safe\";
public String toString() {
return \"s = \" + s;
}
}
WithPrivateFinal
Here's a decompile of WithPrivateFinalField class file (I put it in a separate class for simplicity):
WithPrivateFinalField();
0 aload_0 [this]
1 invokespecial java.lang.Object() [13]
4 aload_0 [this]
5 ldc [8]
7 putfield WithPrivateFinalField.s : java.lang.String [15]
10 return
Line numbers:
[pc: 0, line: 2]
[pc: 4, line: 3]
[pc: 10, line: 2]
Local variable table:
[pc: 0, pc: 11] local: this index: 0 type: WithPrivateFinalField
// Method descriptor #22 ()Ljava/lang/String;
// Stack: 1, Locals: 1
public java.lang.String toString();
0 ldc [23]
2 areturn
Line numbers:
[pc: 0, line: 6]
Local variable table:
[pc: 0, pc: 3] local: this index: 0 type: WithPrivateFinalField
Note in the toString() method, the constant used at address 0 [0 ldc ] shows the compiler already concatenated the string literal "s = " and the private final field " I’m totally safe" together in advance and stored it. The toString() method will always return "s = I’m totally safe" regardless of how the instance variable s changes.