10

I have a constructor

private Double mA;
private Double mB;

Foo(Double a) {
  mA = a;
  mB = a + 10;
}

Foo(Double a, Double b) {
  mA = a;
  mB = b;
  // some logic here
}

if I make a call to second constructor like this:

Foo(Double a) {
  Double b = a + 10;
  this(a, b);
}

than compiler tells me, that constructor should be the first statement. So do I need to copy all logic from the second constructor to first one?

1

3 Answers 3

26

Why don't you just do this(a, a+10) instead?

Note that this() or super() must be the first statement in a constructor, if present. You can, however, still do logic in the arguments. If you need to do complex logic, you can do it by calling a class method in an argument:

static double calculateArgument(double val) {
    return val + 10; // or some really complex logic
}

Foo(double a) {
    this(a, calculateArgument(a));
}

Foo(double a, double b) {
    mA = a;
    mB = b;
}
3
  • It is simplified example. In general I can have something like: b = callToFunction(boo(bar(a))) Oct 14, 2012 at 8:18
  • @nneonneo: +1 for static calculateArgument, non-overridable. Oct 14, 2012 at 8:26
  • 1
    I think it is not because it is non-overridable, but because you just can't call instance method in this()/super()
    – Le_Coeur
    Dec 16, 2013 at 9:43
6

If you use this() or super() call in your constructor to invoke the other constructor, it should always be the first statement in your constructor.

That is why your below code does not compile: -

Foo(Double a) {
  Double b = a + 10;
  this(a, b);
}

You can modify it to follow the above rule: -

Foo(Double a) {
  this(a, a + 10);  //This will work.
}
2

Invocation of another constructor must be the first line in the constructor.

You can call explicit constructor invocation like -

Foo(Double a) {
  this(a, a+10);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.