我理解构造函数链是从最小的构造函数到最大的构造函数。例如
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...");
}
据我所知,对 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
}
第一个构造函数有可能以任何方式调用第二个构造函数吗?
最佳答案
当然。如果你有一个static
函数
JSONObject foo(String)
然后你就可以写了
public Location(String _Name) throws IOException, JSONException {
this(foo(_Name));
}
关于java - 没有 this() 的构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36477259/