Possible Duplicate:
Why does this() and super() have to be the first statement in a constructor?
I'd like to have constructor chain in Java. For example, with the first constructor I have a string as a parameter, and call the second constructor as I create an object from the parameter string.
public class IMethodFinder {
public IMethodFinder(String projectName, String methodName,
int numberOfParameters) {
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
IJavaProject javaProject = JavaCore.create(project);
this(javaProject, methodName, numberOfParameters);
}
public IMethodFinder(IJavaProject javaProject, String methodName,
int numberOfParameters) {
...
}
}
However, I got an error "Constructor call must be the first statement in a constructor" error.
I made a common code that is shared between the two constructors, but I'm not sure this is the only solution to bypass the issue.
public class IMethodFinder {
public IMethodFinder(IJavaProject javaProject, String methodName,
int numberOfParameters) {
dosomething(javaProject, methodName, numberOfParameters);
}
public IMethodFinder(String projectName, String methodName,
int numberOfParameters) {
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
IJavaProject javaProject = JavaCore.create(project);
dosomething(javaProject, methodName, numberOfParameters);
}
private void dosomething(IJavaProject javaProject, String methodName,
int numberOfParameters)
{
...
}
}
- Why does Java require constructor call as the first statement? What's the idea behind this requirement?
- What is Java's convention for my case? Is the calling common method a good way to go?