0

I am new in Java and I am trying to call a constructor inside other constructor. Here is my code:

class TestContructor {
    public TestContructor(){
        String params = "1, 2, 3";
        this(params);
    }
    public TestContructor(String params){
        System.out.println("TestContructor with params: " + params);
    }
}

class TestRunner {
    public static void main(String[] args) {
        new TestContructor();
    }
}

Then I got this error:

javac -g Test.java
Test.java:5: error: call to this must be first statement in constructor
        this(params);
            ^
1 error

And ok, I changed the TestConstructor code:

class TestContructor {
    public TestContructor(){
        // String params = "1, 2, 3";
        this("1, 2, 3"); //Now is the first statement
    }
    public TestContructor(String params){
        System.out.println("TestContructor with params: " + params);
    }
}

And Ok, no problems.

Then, is it a rule in java to call another constructor it must be declared in the first statement line?

What about if I need to do some kind of process before call the other constructor?

I recall I am newer in java programming, but I have this problem and I want to know if it is possible to do that I want.

Robert
  • 10,403
  • 14
  • 67
  • 117

1 Answers1

1

Yes, it's a rule.

If you need to do other work first, your only real option is to refactor that work into another method. Something like:

public TestConstructor(String params) {
    // whatever
}

public TestConstructor(String... paramParts) {
    this(combineParts(paramParts));
}

private static String combineParts(String[] parts) {
    StringBuilder sb = new StringBuilder();
    for (String part : parts) {
        sb.append(part);
    }
    return sb.toString();
}

If you have various computations that depend on one another (for instance, you need to call this(foo, bar) where bar depends on the answer to foo and some other component baz), then you can chain constructors even more. Something like:

public TestConstructor(FooComponent1 f1, FooComponent2 f2, Baz baz) {
    this(createFoo(f1, f2), baz);
}

private TestConstructor(Foo foo, Baz bar) {
    this(foo, createBar(baz));
}

private TestConstructor(Foo foo, Bar bar) {
    // do whatever
}

Note that I've made the helper constructors private. This is particularly useful if Bar is a private inner class, so there's no way for an external caller to create one and pass it in.

yshavit
  • 42,327
  • 7
  • 87
  • 124