Java多构造函数设置问题

Java多构造函数设置问题,java,constructor,Java,Constructor,所以我在使用多个构造函数时遇到了问题。基本上,我有两个WaterDrop构造,其中我将第二个代码块的初始x和y位置传递到相应的构造函数中。问题是它没有将int x,y实例变量设置为适当的起始位置。它在第一个构造函数中设置它们,但是当它使用第二个构造函数绘制点时,它会自动将它们设置为0,0位置。我是否可以调用第一个构造函数,以便它将x和y位置设置为适当的起始位置 public class WaterDrop { // instance variables - replace the example

所以我在使用多个构造函数时遇到了问题。基本上,我有两个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;

}
这是我在WaterCountain课程中传递的内容:


当它使用第二个构造函数绘制点时,它会自动将它们设置为0,0位置,这是因为每次初始化构造函数时,都会创建一个新对象。

你的第二个构造函数不能神奇地知道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;  
}

当你在WaterDropDrawingPanel,boolean move中从未给出一个位置时,你怎么知道合适的起始位置是什么呢?我对此也感到困惑。我在学校,教授说这个起始位置应该由创建水滴对象的对象设置。这意味着需要一个新的构造器,一个允许设置x和y位置的构造器。我的意思是你没有在构造器中证明一个位置,所以如果你不更改构造器参数,就不可能设置位置。因此,您应该期望它是默认值,您将希望为该位置添加参数,但除非有充分的理由,否则我不会这么做。好吧,我是来做这件事的。谢谢你的帮助!那么有没有一个简单的解决方法呢?在下一个构造函数中提供x和y参数。那么,在我将参数添加到新的构造函数中之后,第二个构造函数不是毫无意义吗?是的,当然。
public WaterDrop(int x, int y, DrawingPanel panel, boolean move)
{
    this.x;
    this.y;
    this.panel = panel;  
}