Search code examples
javablackberry-jde

Non-static nested thread - access from another class (Java)


I'm having some trouble creating a thread object in another class (to which it is defined);

It is nested like so:

public final class Sculpture extends UiApplication
{  
     final class ScreenThread extends Thread
     {
        //thread I want to access
     }
}  

So in my other class I want to create the thread object, so I try;

Sculpture.ScreenThread test = (new Sculpture).new ScreenThread();

- This errors (in BlackBerry Eclipse plugin) saying "No enclosing instance of type Sculpture is accessible."

As far as I can tell I can't un-nest this because it causes a lot of the code not to work (I assume it relies on UiApplication), I also can't make it static for the same reason.

Any ideas what I'm doing wrong?

Thanks.


Solution

  • In your current code you define an inner class which requires an instance of the outer, containing class in order to be instantiated:

    ScreenThread screenThread = new Sculpture().new ScreenThread();
    

    If you do not need access to the outer classes context then you may want to define a nested class instead:

    public final class Sculpture extends UiApplication {  
         static final class ScreenThread extends Thread {
            //thread I want to access
         }
    }  
    

    Which you can then import and instantiate 'normally' (ie, without first creating an instance of the outer, containing class):

    ScreenThread screen = new ScreenThread();
    

    One final note, it's generally bad practice to sub-class Thread. It's much better practice to implement Runnable instead.