Pass a class variable to another class

青春壹個敷衍的年華 提交于 2019-12-02 22:01:28

问题


I'd like to pass a class variable to another class and make it a class variable of that class. How would I do this in the following context?

        public class GLCamTest extends Activity {
public float array[] = something;
  }

  class GLLayer extends GLSurfaceView implements SurfaceHolder.Callback,
  Camera.PreviewCallback, Renderer {
  //Get class variable here
 }

回答1:


It is difficult to understand wjat you are asking, but here's a possible answer:

Make class B a subclass of A:

    public class A {
        // Declaration of the 'array' attribute
        public float[] array = new float[]{1.1f, 2.2f, 3.3f};

    }

    class B extends A {
        // Every instance of 'B' also has an 'array' attribute
    }

If array is redeclared to be public static, you get a situation where there is an array attribute that can be referred to as A.array or B.array. (Or within either A or B as just array ... or even as a.array or b.array where a and b have types A and B respectively.)

If you cannot create a direct or subtype relationship between A and B (or A, B and some third class containing the declarations) then you are out of luck. There is no way that they can share declarations.

However, you can use static imports to make it seem like the declaration is shared. For example:

    public class A {
        // Declaration of the 'array' attribute
        public float[] array = new float[]{1.1f, 2.2f, 3.3f};

    }


    import static A.array;
    class B {
        // now I can use 'array' without qualifying it with 'A'
    }

Incidentally, it is generally a bad idea to use static variables to share state, especially state represented as bare arrays. This is distinctly non-object-oriented.




回答2:


Do you have access to instance of A? Or maybe you want array to be static?




回答3:


Do you want the array to be visible everywhere (as if it was a global variable)?

If so then it needs to be static.

But my guess is that you want to pass an instance of GLCamTest on to a GLLayer object, in which case you should use a setter function or pass it in the constructor.

public class GLCamTest extends Activity {
    public float array[] = something;
}

class GLLayer extends GLSurfaceView implements SurfaceHolder.Callback,
    Camera.PreviewCallback, Renderer {
    private GLCamTest camTest;
    public void setCamTest(GLCamTest camTest) {
        this.camTest = camTest;
        // Now you can access the array using camTest.array
    }
}


来源:https://stackoverflow.com/questions/3245028/pass-a-class-variable-to-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!