Search code examples
javavariablesfinal

Is it possible to define a variable only once without using final


I was wondering if there is a way, in Java, to assign a variable only once. I know there is the final keyword but I would like to achieve same result without having to set the value in the constructor. I want to set it outside the constructor, because I don't know the value yet.


Solution

  • You might need check the key before assigning the value, for example:

    Object key;
    
    
    public void setValue(Object value) {
        if (key != null) {
            // ignore or throw exception, depending on your business logic
        } else {
            key = value;
        } 
    }