Joker
Joker

Reputation: 11154

The blank final field name may not have been initialized error

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();
    }
}

Upvotes: 5

Views: 8626

Answers (1)

Darshan Mehta
Darshan Mehta

Reputation: 30839

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();
    }
}

Upvotes: 9

Related Questions