简体   繁体   中英

Java - Any way to make variable unmodifiable after being set in the constructor?

I have a member variable that in a class that I want to make sure nothing changes it after it is set in the constructor. So, it would look something like this:

public class MyClass
{
    private String myVar = null;

    public MyClass(DataObj dataObj)
    {
        myVar = dataObj.getFinalVarValue();
        //at this point I don't want anything to be able change the value of myVar
    }

    ....
}

My first thought was to see I could just add the final modifier to the variable, but the compiler complains about assigning a value to the final field. Is it possible to accomplish this?

The compiler complains (in the constructor), because you already provide an initialization by writing

private String myVar = null;

remove the ' = null ' part. Add final and assign the value in the constructor.

public class MyClass
{
    private final String myVar;

    public MyClass(DataObj dataObj)
    {
        myVar = dataObj.getFinalVarValue(); // the only assignment/init happens here.
    }

    ....
}

Make it private , and then don't include a setter. As long as you never change it in within the class methods, it's immutable.

String objects are already immutable. So adding the private final modificator is enough.

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