2

provided following code the final variable 'map' is consistenly null. But I do not understand why its null, because the method 'add' is only avaible in the class Foo and thus the instance variables should be initiated and in no case be null. Sorry for the long code, but this is the least code you need to reproduce this issue.

Class Bar:

public abstract class Bar {

    private final String dummy;

    public Bar(String dummy) {
        this.dummy = dummy;
        init();
    }

    public void init() {}
}

Class Foo:

public abstract class Foo extends Bar {

    private final String test = "null?";
    private final String dummy2;

    public Foo(String dummy, String dummy2) {
        super(dummy);
        this.dummy2 = dummy2;
    }

    public void check() {
        if(test == null) {
            System.out.println("test is null");
            return;
        }
    }

}

Initiation:

new Foo("dummy", "dummy2") {
    @Override
    public void init() {
        check();
    }
};

This will print consistenly 'test is null' and I can not undestand why.

  • 4
    `init()` is called during `Bar`'s constructor, before the `Foo` fields are initialised. This is why you're advised not to call overridden methods in constructors. See [What's wrong with overridable method calls in constructors?](https://stackoverflow.com/q/3404301/3890632) – khelwood Sep 25 '20 at 09:06
  • Because the super class constructor runs before the field initializers of the subclass, so `init()` and hence `check()` is executed before `test` and `dummy2` are assigned. – Andreas Sep 25 '20 at 09:07
  • You don't have field `map` in your code. – talex Sep 25 '20 at 09:09

0 Answers0