[英]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.