java - 将初始值设置为静态字段

标签 java android static

我有一个类,其中一些变量是用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的参数是SPEEDRADIUS

最佳答案

scale_factor 还必须是 staticfinal,并且必须出现在 SPEED< 的定义之前 在源文件中。

关于java - 将初始值设置为静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22960046/

相关文章:

java - Spring中抛出404并重定向到自定义错误页面

java - 使用 JPA 执行 Select 语句时出错

android - 定期工作请求是否应该立即执行?

android - 在 Android SQLite 数据库中存储值的最快方法?

python扩展模块初始化 - 多个文件

java - Java Swing 在绘画/渲染时是否会阻塞 UI?

java - 使用@GeneratedValue 在@Id 上违反Hibernate 空约束

android - 生成签名 Apk - 任务 ':app:transformClassesWithDexForRelease' 执行失败

c++ - 需要处理 C++ 类成员的静态函数

c++ - constexpr 静态结构类成员的冲突声明