extends Thread null pointer

I created an inner class, that extends Thread. Pretty simple class, I override the run method, which does what I want. However I stored objects of this type in an array, BUT I forgot to do the arrayname = new objectname[10]; or whatever number I wanted. I just declared objectname[] arrayname;

So obviously I should get a null pointer exception if I try arrayname[0] = new objectname(args);

The constructor for the inner class had start(); in it so it began as soon as I created it. With this in the constructor, I still get the exception, but it begins running the Thread anyway??? How can it do this? If I take the start() out of the constructor, and try to do arrayname[0].start(); it does not work as expected. What do I not know about? Just curious, it’s not caused any problems.

I’m not sure what led you to try to start one of the objects in the array rather than the instance of the thread you created. Regardless, take the start out of the constructor – constructors should not be starting new threads or doing anything other than initializing a new instance. Secondly, don’t subclass Thread, use the Thread(Runnable) constructor instead.

That’s because your object is created first THEN it attempts to set it at that index. So your constructor is called, control returns to the “arrayname[0] = …” line, and a NPE is thrown.

Oh I see, thanks ra4king.

Why is that a preferred way sproingie? I’ve seen it in many books so just picked it up from there

The idea is that you’re not changing the behavior of a Thread, just giving it something to run. In practice it often makes no difference; it’s a design thing.

One big reason you should subclass Runnable instead of Thread, other than mere aesthetics, is that it’s much easier to put your Runnables into a java.util.concurrent.ExecutorService later on.