Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The blank final field name may not have been initialized error

Tags:

java

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();
    }
}
like image 226
Sachin Sachdeva Avatar asked Jan 30 '23 03:01

Sachin Sachdeva


1 Answers

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();
    }
}
like image 132
Darshan Mehta Avatar answered Feb 02 '23 10:02

Darshan Mehta