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, Render开发者_如何学编程er {
//Get class variable here
}
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.
Do you have access to instance of A? Or maybe you want array to be static?
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
}
}
精彩评论