Java call constructor from constructor

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 call the second constructor as follows:

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

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

+8
java constructor
source share
3 answers

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

Note that this() or super() must be the first expression in the constructor, if present. However, you can do the logic in the arguments. If you need to execute complex logic, you can do this by calling the class method in the 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; } 
+21
source share

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

This is why your below code does not compile: -

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

You can change it to follow the rule above: -

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

The call to another constructor should be the first line in the constructor.

You can call an explicit constructor call, for example -

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

All Articles