Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a variable final in any given moment (after initialization and eventual code)

Is it possible to make a variable final in any given moment? I would like to decide when its immutable, not just with the first assignment.

It would be perfect, if null would not count as an assignment. So if you would initialize it with null, you would still have a wildcard for the first assignment after some code, not necessarily in the constructor.

like image 291
Whimusical Avatar asked Jul 25 '12 12:07

Whimusical


4 Answers

Once you assign a final variable, you can never change its value, as stated here:

A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable.

If you want to have a variable which at a given point in time can be made immutable, what you can do is something like so:

...
private boolean isMutable;
private String someString;

public void setMutable(boolean value)
{
    this.isMutable = value;
}

public void setSomeString(String value)
{
    if (this.isMutable)
    {
        this.someString = value;
    }
}

...
like image 55
npinti Avatar answered Nov 08 '22 23:11

npinti


No you cannot. What you can do is encapsulating it withing a method:

public boolean setValue(int i)
{
    if(isMutable)
    {
        value = i;
        return true;
    }
    return false;
}
like image 29
Eng.Fouad Avatar answered Nov 08 '22 23:11

Eng.Fouad


It should be done when the variable is being declared, therefore it is not possible to make an already declared variable final.

like image 3
vahidg Avatar answered Nov 08 '22 21:11

vahidg


Just for you to know, the feature is now proposed in a draft: http://openjdk.java.net/jeps/309. It's called dyanmic constant. Check future work section:

  • Surfacing the lazy initialization of constants in the Java language

The value is, therefore, dynamic but, since its value is only set once, it is also constant.

like image 2
Whimusical Avatar answered Nov 08 '22 22:11

Whimusical