Following code is giving compilation error mentioned below at line 1
The blank final field name may not have been initialized
My question is why is this error there as i have already initialized field in its constructor.
public class Test1 {
private final String name;
public Test1() {
name = "abc";
}
@SuppressWarnings("rawtypes")
private final Function fs = n -> {
System.out.println(this.name);// Line 1
return n;
};
public static void main(String[] args) {
new Test1();
}
}
During object creation, instance initialisers (i.e. assignments to instance variables and initialisation blocks) get executed before a constructor runs and hence, they would need the values to be initialised by then. Following should work:
public class Test1 {
private final String name;
public Test1() {
name = "abc";
fs = n -> {
System.out.println(this.name);// Line 1
return n;
};
}
@SuppressWarnings("rawtypes")
private final Function fs;
public static void main(String[] args) {
new Test1();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With