2

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

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

I tried to write something like this and got horribly muddled. Thanks for a clear concise explanation, it's obvious to me now!
"the compiler replaces the constant name everywhere in the code [...] during compilation" is simply not true. If you initialize it e.g. with the value from a static function the right hand side of the assignment is no longer a constant expression and can't be inlined by the compiler (JIT compilation may be a different story).
0

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

1 Comment

Worth noting that static contexts are messy, hard to test and debug, and should be avoided if at all possible.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.