简体   繁体   中英

I need to use a non-static variable inside a static class… How to get around this?

Here's kind of an outline of the relevant problem:

public class Foo extends Activity{

    Cursor myCursor;

    public void onCreate(Bundle savedInstanceState) {
        //I initialize myCursor here
    }

    public void setCursor(){
        //When we are interested in a different set of data, the cursor changes here
    }

    public static class MySurfaceView extends SurfaceView implements Runnable{
        public void run(){
            //I need to access myCursor here
        }
    }
}

I know I cannot access a non-static variable from within a static class, but I can't make myCursor static because it would require changing almost all of my functions to static. Any tips?

Why is the inner class static? If you remove the static modifier then it will have access to its enclosing class and subsequently to myCursor.

If it has to be static then you could just pass in the necessary Foo object into its constructor and use that as your reference to the enclosing class. Not as neat but it should still work.

Regardless, static (on a field) means it belongs to the class not the object. You may be getting confused with final which means the reference can't be modified?

On an inner class, it behaves differently (and not necessarily logically!) It removes the reference from the inner class to the outer class, so it's essentially a completely separate class just sitting within another.

If you want a more detailed answer, you'll have to provide more details about the context of your applciation - it's difficult to say what should and shouldn't be static just from that code snippet.

Couple of choices

  1. Pass Foo ( or directly myCursor ) object to MySurfaceView constructor.
  2. Make MySurfaceView non-static

Static nested classes do not have access to other members of the enclosing class, as stated in the java tutorials , which makes me wonder why do you need MySurfaceView class to be static? You can just make it a nested class

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