abstract class ThreadTest implements Runnable
{
Thread thread;
ThreadTest()
{
thread = new Thread(this);
thread.start();
}
public void run()
{
while (true)
{
update();
try { Thread.sleep(500); } catch (InterruptedException e) {}
}
}
abstract void update();
public static void main(String[] args)
{
new SubTest();
}
}class SubTest extends ThreadTest
{
Person p = new Person();
void update()
{
//fixes the NullPointerException.
//if (p != null)
p.update();
}
}class Person
{
int age = 0;
void update()
{
age++;
System.out.println(age);
if (age >= 5)
System.exit(0);
}
}SubTest's update method will regernate a Nullpointerexception when running at this state because reference p is apperently null when runned. But how can reference p ever be null really? When a new object of SubTest is created reference p should directly be initialized a value (new Person) because its written in class definition?I noted that this can be worked around by adding
if (p != null)to check if p is null, and if so, skip updating this round. What am I missing to understand here? Is the update method called in SubTest before like the whole "creation" of the object is complete so for a short time p equals null instead a of a Person object?
A bigger project of mine is built up on this kind of thread-looping and I have to to put in if-statements everywhere to check if references really pointing at a object when they are used. This feels like a bad way doing it, how can I solve this in a more "corect way"?
Thanks in advance!
Same question discussed:
Nullpointerexception when using a looping thread (Java in General forum at JavaRanch)
OTN Discussion Forums : NullpointerException when using a ...
Edited by Cander, 25 November 2010 - 02:10 PM.


Sign In
Create Account


Back to top









