简体   繁体   中英

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.

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.

You aren't creating your Sculpture . The call should look like new Sculpture().new ScreenThread() .

看起来您只是忘记了new Sculpture之后的()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM