1

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.

lmat - Reinstate Monica
  • 7,289
  • 6
  • 48
  • 62

1 Answers1

7

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;
  }
}
lmat - Reinstate Monica
  • 7,289
  • 6
  • 48
  • 62
  • 14
    Feeling a bit schizophrenic? – Matt Ball Sep 06 '12 at 18:57
  • What makes the original chaining incorrect? Is there something in the Java spec that indicates that you cannot chain as indicated? – Eric B. Sep 06 '12 at 19:06
  • 1
    @EricB. The problem in this case is, that his variable **val** is a final variable. It can be assigned only **once**. So, if he calls the no-arg constructor from his other constructer, the variable is assigned the value _null_. He then attempts to assign it the value of the _parameter val_, which he can't because he declared the variable as final. This leads to a compilation error. – Sebastian_H Sep 06 '12 at 19:19
  • @Sebastian_H Of course. I missed the final keyword. Thanks. – Eric B. Sep 07 '12 at 00:43