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

后端 未结 12 1579
感情败类
感情败类 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:30

    Marking a field private and not exposing a setter should be sufficient:

    public class Example{ 
    
    private long id=0;  
    
       public Example(long id)  
       {  
           this.id=id;
       }    
    
    public long getId()  
    {  
         return this.id;
    }  
    

    if this is insufficient and you want someone to be able to modify it X times you can do this:

    public class Example  
    {  
        ...  
        private final int MAX_CHANGES = 1;  
        private int changes = 0;    
    
         public void setId(long id) throws Exception {
            validateExample(); 
            changes++; 
            if ( this.id == 0 ) {
                this.id = id;
            } else {
                throw new Exception("Can't change id once set");
            }
        }
    
        private validateExample  
        {  
            if(MAX_CHANGES==change)  
            {  
                 throw new IllegalStateException("Can no longer update this id");   
            }  
        }  
    }  
    

    This approach is akin to design by contract, wherein you validate the state of the object after a mutator (something that changes the state of the object) is invoked.

提交回复
热议问题