Search code examples
javaconstructorconstructor-chainingvariable-initialization

Variable might already have been assigned


The following code has an error:

class A
{

  private final String val;

  public A(){
    this.val = null;
  }

  public A(String val){
    this();
    this.val = val;
  }
}

the error is "variable val might already have been assigned

Is there a workaround for this error without re-writing any code that may be in the default constructor? This is a minimum working example; if you're asking yourself "What code in the default constructor", keep in mind that a real example could have a good deal of code that you wouldn't want to repeat in other constructors (assigning other final variables, etc.).

Please also remember that this is a minimum example, and the same problem exists with a large number of constructors.


Solution

  • You're chaining in the wrong direction. This took me a while to figure out, too, but change your example like so:

    class A
    {
    
      private final String val;
    
      public A(){
        this(null);
      }
    
      public A(String val){
        this.val = val;
      }
    }