title: How to create a variable that can be set only once but isn't final in Java
body: <p>I want a class that I can create instances of with one variable unset (the <code>id</code>), then initialise this variable later, and have it <strong>immutable after initialisation</strong>. Effectively, I'd like a <code>final</code> variable that I can initialise outside of the constructor.</p>
  
  <p>Currently, I'm improvising this with a setter that throws an <code>Exception</code> as follows:</p>
  
  <pre><code>public class Example {
  
      private long id = 0;
  
      // Constructors and other variables and methods deleted for clarity
  
      public long getId() {
          return id;
      }
  
      public void setId(long id) throws Exception {
          if ( this.id == 0 ) {
              this.id = id;
          } else {
              throw new Exception("Can't change id once set");
          }
      }
  }
  </code></pre>
  
  <p>Is this a good way of going about what I'm trying to do? I feel like I should be able to set something as immutable after it's initialised, or that there is a pattern I can use to make this more elegant.</p>