简体   繁体   English

Java最终变量初始化

[英]Java Final Variable Initialization

I get an error that says that the size variable might not have been initialized even though i have initialized it in the constructor. 我收到一条错误消息,即使我已在构造函数中将其初始化,也可能尚未初始化size变量。 why doesn't this work ?= 为什么这行不通?=

public class Ore {

protected static final float size;
protected String name;
protected int itemID;
protected ArrayList<Mineral> minerals;

public Ore(float size, String name, int itemID){
       this.size = size;
       this.name = name;
       this.itemID = itemID;
    }

    public String getPrizeData(int itemNumber){
       String data = null;

       return data;
    }

    public float getPrice(){
        float price = 0;

        return price;
    }
}

从大小中删除static修饰符...我很确定你不想要它;)

protected static final float size;

Combination of final and static is considered CONSTANT in java and the Compiler replaces the constant name ( Here size ) everywhere in the code with its value during compilation so it's not allowed here to initialize it in constructor and generates compile time error. 在Java中, finalstatic组合被认为是常量 ,并且编译器在编译期间将代码中的常数名称( 此处为 size )替换为其值,因此此处不允许在constructor函数中对其进行初始化并生成编译时错误。


So either go for the vikingsteve's solution or initialize it at the time of declaration. 因此,要么寻求vikingsteve的解决方案,要么在声明时进行初始化。

size is a static field. size是一个静态字段。 As such it has to be initialized directly in the declaration or form a static initializer, ie like this: 因此,必须直接在声明中对其进行初始化,或者形成一个静态初始化程序,即:

public class Ore {

    protected static final float size;

    static{
        size = // add something here
    }
    //....
}

The way you have things it would be possible to derive a class from Ore and implement a public static function in that derived class that refers to size . 你有事情的方式, 可能从一类Ore在派生类指和实施公共静态函数size This is one way in which size could be accessed prior to initialisation and the compiler is correctly identifying that. 这是在初始化之前可以访问size一种方式,编译器可以正确地识别大小。

One fix would be to use a static initialiser block in Ore which initialises size , or set its value to a literal: protected static final float size = /*ToDo - a literal here*/; 一种解决方法是在Ore使用静态初始化程序块来初始化size ,或者将其值设置为文字: protected static final float size = /*ToDo - a literal here*/;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM