[英]Can't initialize static final field in constructor
为什么在以下情况下不允许分配最终修饰符:
public static final float aspectRatio;
public TestBaseClass() {
// TODO Auto-generated constructor stub
screenWidth = Gdx.graphics.getWidth();
screenHeight = Gdx.graphics.getHeight();
aspectRatio = screenWidth/screenHeight;
}
我想当我将变量声明为final并将其保留为空白(未初始化)时,我需要在构造函数中添加一个值,因为它是第一个被调用的类,并且每个类都有一个。
但是我从eclipse中收到一条错误消息: The final field TestBaseClass.aspectRatio cannot be assigned
。
为什么?
aspectRatio
是static
,但是您尝试在构造函数中对其进行初始化,该构造函数将在每次创建新实例时进行设置。 根据定义,这不是最终的。 请尝试使用静态初始化块。
public static final float aspectRatio;
static {
screenWidth = Gdx.graphics.getWidth();
screenHeight = Gdx.graphics.getHeight();
aspectRatio = screenWidth/screenHeight;
}
public TestBaseClass() {
// Any instance-based values can be initialized here.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.