How to create a variable that can be set only once but isn't final in Java

后端 未结 12 1603
感情败类
感情败类 2020-12-14 05:43

I want a class that I can create instances of with one variable unset (the id), then initialise this variable later, and have it immutable after initial

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 06:33

    You can simply add a boolean flag, and in your setId(), set/check the boolean. If I understood the question right, we don't need any complex structure/pattern here. How about this:

    public class Example {
    
    private long id = 0;
    private boolean touched = false;
    
    // Constructors and other variables and methods deleted for clarity
    
    public long getId() {
        return id;
    }
    
    public void setId(long id) throws Exception {
        if ( !touchted ) {
            this.id = id;
             touched = true;
        } else {
            throw new Exception("Can't change id once set");
        }
    }
    
    }
    

    in this way, if you setId(0l); it thinks that the ID is set too. You can change if it is not right for your business logic requirement.

    not edited it in an IDE, sorry for the typo/format problem, if there was...

提交回复
热议问题