[英]Any way to call the default constructor from a parameterized constructor?
假設我有以下代碼
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)
調用main(default)構造函數?
或者我只是將整個內容從main(默認)構造函數復制粘貼到參數化的結構,如上面代碼中的注釋所示?
在參數化構造函數中設置了變量i
和s
之后,我需要調用默認構造函數,因為處理涉及這些變量。
我看到這篇文章 ,說將this()
作為第一行將調用默認構造函數。 但是我需要在設置值后調用它。
調用this()
會起作用,但是請注意,它必須是構造函數中的第一條語句。 例如:下面的代碼將是非法的,將無法編譯:
class Test {
void Test() { }
void Test(int i) {
i = 9;
this();
}
}
一種選擇是從默認構造函數調用參數化構造函數。
C(){
this(0, "Blank");
}
C(int i){
this(i,"Blank");
}
C(int i, String s){
this.i = i;
this.s = s;
}
通過該模式,您可以為構造函數提供默認值,而為更具體的構造函數提供較少的參數。
另外,注釋鏈構造器必須作為另一個構造器中的第一個調用完成-初始化變量后不能調用另一個構造器:
C(int i, String s){
this.i = i;
this.s = s;
this(); // invalid!
}
如果您確實想做這樣的事情,請考慮使用init方法:
C() {
init();
}
C(int i, String s) {
this.i = i;
this.s = s;
init();
}
調用this()
作為其他構造函數中的第一條語句就足夠了。
C(int i, String s)
{
this();
// other stuff.
}
引用文檔:
另一個構造函數的調用必須是該構造函數的第一行 。
所以沒有不可能。 在第一行中使用this()。
您可以將所有代碼從主構造函數移至某個方法,例如mainProcessing()。
C()
{
System.out.println("In main constructor");
mainProcessing();
}
private void mainProcessing()
{
// Move your code from main constructor to here.
}
現在,在參數化的構造函數2中,可以在所需位置調用此方法mainProcessing()。
C(int i, String s)
{
System.out.println("In parameterized constructor 2");
this.i = i;
this.s = s;
mainProcessing();
}
只需調用構造函數ny this();即可。 聲明作為默認構造函數的第一行。
您可以使用this();
調用默認構造函數
C(int i, String s){
this(); // call to default constructor
// .....
}
在參數化構造函數的第一行中使用this()
C(int i, String s){
this();
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?
}
您可以在第一條語句中調用this()
以在任何參數化的構造函數中調用默認構造函數。
請注意, this()
必須強制為構造函數定義的第一行
C(int i, String s){
this();
. . . .
}
但是我需要在設置值后調用它。
這不可能。 構造函數調用必須是第一個語句。
您可以通過以下鏈接: 構造函數調用必須是第一行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.