您好,我創建了一個類,其中有 2 個像這樣的建構式:
public class Test {
int speed;
int id;
int height = 0;
Test(final int speed, final int id, final int height) {
this.speed = speed;
this.id = id;
this.height = height;
}
public Test buildFor(final int speed, final int id) {
return new Test(speed, id, 5);
}
public void show() {
System.out.println(this.speed);
System.out.println(this.id);
System.out.println(this.height);
}
}
主要是我嘗試創建一個這樣的物件:
public static void main (String[] args) {
System.out.println("Hello World!");
Test testObject = new Test(4,4);
testObject.show();
}
但它在這一行失敗了: Test testObject = new Test(4,4); 什么是BuildFor什么不對的代碼?
uj5u.com熱心網友回復:
buildFor是一個方法,而不是一個建構式。因此,您不能像使用new關鍵字的建構式一樣呼叫該方法。
看起來您正在嘗試鏈接您的建構式。
正確的做法是:
public Test(final int speed, final int id) {
this(speed, id, 5);
}
這是一個帶有 2 個引數的建構式,它在內部呼叫另一個帶有 3 個引數的建構式,傳遞它接收到的 2 個引數,最后一個引數的默認值為 5。
uj5u.com熱心網友回復:
您收到錯誤的原因是您將兩個引數而不是三個引數傳遞到建構式中。您可以為這種情況創建另一個建構式:
public class Test {
int speed;
int id;
int height = 0;
Test(final int speed, final int id, final int height) {
this.speed = speed;
this.id = id;
this.height = height;
}
Test(final int speed, final int id) {
this.speed = speed;
this.id = id;
}
public Test buildFor(final int speed, final int id) {
return new Test(speed, id, 5);
}
public void show() {
System.out.println(
this.speed
);
System.out.println(
this.id
);
System.out.println(
this.height
);
}
}
此外,方法 buildFor() 不是建構式,因此如果您希望它運行,則必須手動呼叫它。
我希望這有幫助!如果您有任何其他問題/說明,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/380772.html
標籤:爪哇
