Orange Peel
Orange Peel

Reputation: 484

Call another constructor from constructor after other instructions

I have 2 constructors, accepting different types of arguments:

public Board(String s) {

    // the string is parsed to an int array.
    int[] array = doSomething(s);

    this(array);
}

public Board(int[] array) {
    doSomethingElse(s);
}

However on the first constructor I get "Constructor call must be the first statement in a constructor". Is there a way to have a constructor call another after performing other actions, or is it simply a limitation of Java?

Upvotes: 1

Views: 808

Answers (4)

Razib
Razib

Reputation: 11153

Yes in java when you call constructor from another constructor then the constructor call should be the first statement. Look at the following code snippet and the comments -

public class Board{

   //no-argument consturctor
   public Board(){
         //if the 'Board' class has a super class
        //then the super class constructor is called from here
       //and it will be the firs statement
       //the call can be explicit or implicit

      //Now do something
   } 

  public Board(int size){
     //call to no-arg constructor 

     this(); // explicit call to the no-argument constructor - 'Board()'
     //Now you can do something
     //but after doing something you can not 
     //make an explicit/implicit constructor call.
  }
}

Upvotes: 0

Tagir Valeev
Tagir Valeev

Reputation: 100149

No, you cannot call the constructor after doing something else in another constructor. Constructor is very special method in Java. However you have two options:

1. If everything you want to do before calling another constructor is to preprocess parameters, you can write like this:

public Board(String s) {
    this(doSomething(s));
}

private static int[] doSomething(String s) {...}

You can call any static methods and pass their results to another constructor.

2. If your preprocessing implies modification of current object, so you cannot do this with static methods, you can call the special method (like init() from both constructors):

public Board(String s) {
    int[] array = doSomething(s);

    init(array);
}

public Board(int[] array) {
    init(array);
}

private void init(int[] array) {
    // do something else
}

Upvotes: 3

rafaelc
rafaelc

Reputation: 59274

As a rule of Java, this should be called first:

public Board(String s) {
    this(doSomething(s));
}

Upvotes: 2

Raphael Amoedo
Raphael Amoedo

Reputation: 4455

It doesn't have to be a constructor. You can do like:

public Board(String s) {

    // the string is parsed to an int array.
    int[] array = doSomething(s);

    this.sharedMethod(array);
}

public Board(int[] array) {
    this.sharedMethod(array);
}

public void sharedMethod() {
 //yourLogic
}

Upvotes: 1

Related Questions