Skretch
Skretch

Reputation: 69

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;
    }
}

Upvotes: 2

Views: 125

Answers (4)

Bathsheba
Bathsheba

Reputation: 234665

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

Upvotes: 0

Akash Thakare
Akash Thakare

Reputation: 22972

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.

Upvotes: 1

fabian
fabian

Reputation: 82461

size is a static field. As such it has to be initialized directly in the declaration or form a static initializer, i.e. like this:

public class Ore {

    protected static final float size;

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

Upvotes: 0

vikingsteve
vikingsteve

Reputation: 40388

drop the static modifier from size... I'm pretty sure you don't want it there ;)

Upvotes: 4

Related Questions