将类变量传递给另一个类 [英] Pass a class variable to another class
问题描述
我想将一个类变量传递给另一个类,并使其成为该类的类变量。我将如何在以下上下文中执行此操作?
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
}
推荐答案
很难理解你问的问题,但这里有可能回答:
It is difficult to understand wjat you are asking, but here's a possible answer:
使B类成为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
}
如果数组
重新声明为 public static
,你会遇到一个 array
属性的情况,可以称为 A.array
或 B.array
。 (或者在 A
或 B
内,只需数组
。 ..或者甚至作为 a.array
或 b.array
其中 a
和 b
分别具有类型 A
和 B
。)
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.)
如果您无法在 A
和 B <之间创建直接或子类型关系/ code>(或
A
, B
和一些包含声明的第三类)然后你就没了运气。他们无法分享声明。
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'
}
顺便说一句,使用 static
变量来共享状态通常是一个坏主意,尤其是表示为裸阵列的状态。这显然是非面向对象的。
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.
这篇关于将类变量传递给另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!