【发布时间】:2013-01-03 16:46:16
【问题描述】:
假设,我有以下代码
class C {
int i;
String s;
C(){
System.out.println("In main constructor");
// Other processing
}
C(int i){
this(i,"Blank");
System.out.println("In parameterized constructor 1");
}
C(int i, String s){
System.out.println("In parameterized constructor 2");
this.i = i;
this.s = s;
// Other processing
// Should this be a copy-paste from the main contructor?
// or is there any way to call it?
}
public void show(){
System.out.println("Show Method : " + i + ", "+ s);
}
}
我想知道,有什么办法,我可以从参数化构造函数(即C(int i, String s) 在这种情况下)调用主(默认)构造函数吗?
或者我只是将主(默认)构造函数中的全部内容复制粘贴到参数化的构造函数中,如上述代码中的 cmets 所示?
注意
我需要在参数化构造函数中设置变量i和s后调用默认构造函数,因为处理涉及到这些变量。
编辑
我看到this post,它说将this() 作为第一行将调用默认构造函数。但是我需要在设置值之后调用它。
【问题讨论】:
标签: java default-constructor parameterized-constructor