我知道构造函数链是从最小的构造函数到最大的构造函数.例如
public MyChaining(){
System.out.println("In default constructor...");
}
public MyChaining(int i){
this();
System.out.println("In single parameter constructor...");
}
public MyChaining(int i,int j){
this(j);
System.out.println("In double parameter constructor...");
}
Run Code Online (Sandbox Code Playgroud)
另外据我所知,调用this()并且super()必须在第一行.但绕过那个限制和链构造函数是否可能(并且如果是,是否有效)?
例如,我有两个共享一些代码的构造函数.
public Location(String _Name) throws IOException, JSONException {
//Three lines of unique code (must be executed before the shared code)
//Shared code
}
public Location(JSONObject json) {
//Shared code
}
Run Code Online (Sandbox Code Playgroud)
第一个构造函数可以以任何方式调用第二个构造函数吗?
当然。如果你有一个static函数
JSONObject foo(String)
那么你可以写
public Location(String _Name) throws IOException, JSONException {
this(foo(_Name));
}
Run Code Online (Sandbox Code Playgroud)