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

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

    Let me suggest you a little bit more elegant decision. First variant (without throwing an exception):

    public class Example {
    
        private Long id;
    
        // Constructors and other variables and methods deleted for clarity
    
        public long getId() {
            return id;
        }
    
        public void setId(long id) {
            this.id = this.id == null ? id : this.id;
        }
    
    }
    

    Second variant (with throwing an exception):

         public void setId(long id)  {
             this.id = this.id == null ? id : throw_();
         }
    
         public int throw_() {
             throw new RuntimeException("id is already set");
         }
    

提交回复
热议问题