Java has fewer quirks compared to C++, but sometimes I do come across surprises.
A code like following will fail to compile since you are trying to initialize a variable with an uninitialized variable.
1
2
3
4
5
6
7
8
9
| public class Sample {
private final String mField1;
private final String mField2 = mField1 + " two";
private Sample(String field1) {
mField1 = field1;
}
}
|
But if instead of directly referencing mField1, you reference indirectly via a getter method code will compile, and mField2 will get “null” value for mField1.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| public class Sample {
private final String mField1;
private final String mField2 = getField1() + " two";
private Sample(String field1) {
mField1 = field1;
}
private String getField1() {
return mField1;
}
private String getField2() {
return mField2;
}
public static void main (String[] args) {
Sample sample = new Sample("one");
// prints "Field 1 is one"
System.out.println("Field 1 is " + sample.getField1());
// prints "Field 2 is null two"!!!
System.out.println("Field 2 is " + sample.getField2());
}
}
|