Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: initialized inline private final field is null [duplicate]

I cannot understand why a private variable is null even if it's initialized inline. Here a snippet of my code:

public abstract class A {
    public A() {
        initialize();
    }

    protected abstract void initializeLayout();
    protected void initialize() {
        // Do something
        initializeLayout();
    }
}

public abstract class B extends A {
    private final Object myVariable = new Object();

    @Override
    protected void initializeLayout() {
        // Do something with myVariable
    }
}

Well, when this code reaches B.initailizeLayout, myVariable is NULL. I thought inline field were initialized before everything else, even before constructor. Am I wrong with something?

like image 406
nicecatch Avatar asked Nov 18 '15 15:11

nicecatch


1 Answers

The constructor of the super class A (which calls initialize() which calls B's initializeLayout()) is executed before the instance variables of the sub-class B are initialized. Therefore your instance variable myVariable is still null at that time.

like image 166
Eran Avatar answered Sep 30 '22 17:09

Eran