Reputation: 484
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
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
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:
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.
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
Reputation: 59274
As a rule of Java
, this
should be called first:
public Board(String s) {
this(doSomething(s));
}
Upvotes: 2
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