简体   繁体   中英

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. 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.


So either go for the vikingsteve's solution or initialize it at the time of declaration.

size is a static field. 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 . This is one way in which size could be accessed prior to initialisation and the compiler is correctly identifying that.

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*/;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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