![](/img/trans.png)
[英]Setting Up a Constructor and Array List to Accept Multiple Parameters (Java)
[英]Java Multiple Constructor Setting Issue
所以我在使用多個構造函數時遇到問題。 基本上,我有兩個WaterDrop構造,將初始的x和y位置(第二個代碼塊)傳遞到適當的構造函數中。 問題是它沒有將int x,y實例變量設置為適當的起始位置。 它在第一個構造函數中將它們設置為精細,但是在使用第二個構造函數繪制點時,它將自動將它們設置為(0,0)位置。 無論如何,我可以調用第一個構造函數,以便將x和y位置設置為適當的起始位置嗎?
public class WaterDrop
{
// instance variables - replace the example below with your own
private int x;
private int y;
private int xVelocity;
private int yVelocity;
private DrawingPanel panel;
private static int DIAMETER = 1;
private int delayStart;
private int bounceLimit;
private static Random rand = new Random();
public WaterDrop(int x, int y){
this.x = x; //**These assign just fine but I can't get them to get passed**
this.y = y; //**into the next WaterDrop constructor**
//**i.e. (200, 400)**
}
public WaterDrop(DrawingPanel panel, boolean move)
{
//initialise instance variables //**In this constructor they are still**
//**initialized to 0**
this.panel = panel; //**Since they are initialized at 0, when I draw the**
//**waterDrops they appear at the location (0, 0)**
}
xVelocity = rand.nextInt(3) - 1;
yVelocity = rand.nextInt(20) + 1 ;
delayStart = rand.nextInt(100);
bounceLimit = 0;
}
這是我從WaterFountain類中傳入的內容:
public class WaterFountain{
....
public WaterFountain(DrawingPanel panel, int xLocation, int yLocation)
{
this.panel = panel;
this.xLocation = xLocation;
this.yLocation = yLocation;
for(int i = 0; i < NUM_WATER_DROPS; i++){
waterDrop[i] = new WaterDrop(this.xLocation, this.yLocation);
}
}
....
}
您的第二個構造函數不能僅僅神奇地“知道” x
和y
的適當值。 您必須為其提供適當的值。 唯一的方法是向其中添加int x
和int y
參數。 然后,可以通過調用第一個構造函數來設置x
和y
實例變量:
public WaterDrop(int x, int y, DrawingPanel panel, boolean move)
{
this(x, y); // invoke the WaterDrop(int, int) ctor
this.panel = panel;
}
或者直接設置x
和y
:
public WaterDrop(int x, int y, DrawingPanel panel, boolean move)
{
this.x;
this.y;
this.panel = panel;
}
“使用第二個構造函數繪制點時,它會自動將它們設置為(0,0)位置”,這是因為每次初始化構造函數時都會創建一個新對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.