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?
Invocation of another constructor must be the first line in the constructor.
You can call explicit constructor invocation like -
Why don't you just do
this(a, a+10)
instead?Note that
this()
orsuper()
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:If you use
this()
orsuper()
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: -
You can modify it to follow the above rule: -