Let's say we have a class:
public class MyClass extends AbstractClass {
private AnotherObject ao = null;
public MyClass() {
super();
}
@Override
protected void init() {
ao = new AnotherObject();
if (ao != null) {
log.info("NOT NULL");
}
}
@Override
protected void doSomething() {
if (ao == null) {
log.info("It is NULL.");
}
ao.doIt(); //NullPointerException here
}
}
And the corresponding abstract class:
public class AbstractClass implements Runnable {
Thread myThread = null;
AbstractClass () {
init();
myThread = new Thread(this, "ThreadName");
myThread.start();
}
public void run() {
while(true) {
doSomething();
Thread.sleep(1000);
}
}
protected abstract void init();
protected abstract void doSomething();
}
The constructor of MyClass
calls the parent's constructor and the parent's constructor calls the init()
method. This init
method initializes the ao
variable and therefore the log shows, that this ao
object is NOT null.
After this, the parent's constructor creates a thread and this thread will execute the while
loop, which calls doSomething()
. In this overridden method, the ao
object is used, but this ao
object is suddenly null.
Can somebody explain me the ao
object is set and then suddenly it is null?