【发布时间】:2015-07-02 08:36:02
【问题描述】:
我是 Java 新手,我正在尝试在其他构造函数中调用构造函数。这是我的代码:
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();
}
}
然后我得到了这个错误:
javac -g Test.java
Test.java:5: error: call to this must be first statement in constructor
this(params);
^
1 error
好的,我更改了 TestConstructor 代码:
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);
}
}
好吧,没问题。
那么,在java中调用另一个构造函数是不是一个规则,它必须在第一行声明?
如果我需要在调用另一个构造函数之前做一些处理呢?
我记得我是 java 编程的新手,但我遇到了这个问题,我想知道是否有可能做到我想要的。
【问题讨论】:
标签: java syntax constructor compiler-errors syntax-error