简体   繁体   中英

Java Multiple Constructor Setting Issue

So I am having issues with the multiple constructors that I am using. Basically, I have two WaterDrop constructs where I pass in the initial x and y position (second block of code) into the appropriate constructor. The issue is that it doesn't set int x, y instance variables to the appropriate starting positions. It sets them fine the the first constructor but then when it draws the dots, using the second constructor, it automatically sets them to the (0, 0) position. Is there anyway I could call the first constructor so it sets the x and y position to the appropriate starting location?

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;

}

This is what I'm passing in from the WaterFountain class:

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);
    }
}


....
}

Your second constructor can't just magically "know" the appropriate values for x and y . You have to give it the appropriate values. And the only way to do that is to add int x and int y arguments to it. Then, you can set the x and y instance variables either by invoking the first constructor:

public WaterDrop(int x, int y, DrawingPanel panel, boolean move)
{
    this(x, y);  // invoke the WaterDrop(int, int) ctor
    this.panel = panel;  
}

or just set x and y directly:

public WaterDrop(int x, int y, DrawingPanel panel, boolean move)
{
    this.x;
    this.y;
    this.panel = panel;  
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM