我有一个类,其中一些变量是用static final
初始化的。该变量有一个已定义的初始值,该初始值在同一个类和另一个类中使用。
现在,我希望该变量的值取决于比例因子:
从此:
class Ball {
public static final float SPEED = 4.0f;
//...
对此:
class Ball {
public static final float SPEED = 4.0f * scale_factor;
//...
假设 scale_factor
是另一个 float ,其值在 1.0 到 3.0 之间。
问题是,如果我这样做,我会收到此错误:
The field SPEED cannot be declared static in a non-static inner type,
unless initialized with a constant expression
建议去掉SPEED的静态修饰符。如果我这样做,那么我就不能在其他类中使用这个变量,因为它告诉我将其设为静态才能使用它。
更新--
public class SinglePlayerView extends View {
//...
public static float scale_factor;
//...
public SinglePlayerView(Context context) {
super(context);
scale_factor = setScreenScale();
}
public float setScreenScale() {
float scale = getResources().getDisplayMetrics().density;
return scale;
}
class Ball {
public float x, y, xp, yp, vx, vy;
public float speed = SPEED;
public static final double BOUND = Math.PI / 9;
public static final float SPEED = 4.0f;
public static final int RADIUS = 4;
public static final double SALT = 4 * Math.PI / 9;
public Ball() {
}
public Ball(Ball other) {
x = other.x;
y = other.y;
xp = other.xp;
yp = other.yp;
vx = other.vx;
vy = other.vy;
speed = other.speed;
mAngle = other.mAngle;
}
//...
我需要乘以scale_factor的参数是SPEED
和RADIUS
最佳答案
scale_factor
还必须是 static
和 final
,并且必须出现在 SPEED< 的定义之前
在源文件中。
关于java - 将初始值设置为静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22960046/