So habe ich Probleme mit den mehreren Konstruktoren, die ich verwende. Grundsätzlich habe ich zwei WaterDrop-Konstrukte, bei denen ich die anfängliche x- und y-Position (zweiter Block des Codes) in den entsprechenden Konstruktor übergebe. Das Problem ist, dass int x, y Instanzvariablen nicht auf die entsprechenden Startpositionen gesetzt werden. Sie setzt den ersten Konstruktor in Ordnung, aber beim Zeichnen der Punkte mit dem zweiten Konstruktor werden sie automatisch auf die Position (0, 0) gesetzt. Kann ich den ersten Konstruktor trotzdem aufrufen, so dass er die x- und y-Position auf die entsprechende Startposition setzt?Java Multiple Constructor Einstellung Problem
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;
}
Dies ist, was in der Wasserfontäne Klasse ich vorbei:
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);
}
}
....
}
Wie würden Sie wissen, was das * "geeignete Ausgangsposition "* ist, wenn Sie niemals eine Position in' WaterDrop (DrawingPanel panel, boolean move) 'angeben? –
Ich bin auch davon verwirrt. Ich bin in der Schule und der Professor sagte: "Dieser Startort sollte durch das Objekt festgelegt werden, das die WaterDrop-Objekte erstellt. Das bedeutet, dass ein neuer Konstruktor benötigt wird, einer, der das Setzen der x- und y-Position erlaubt." – user8865807
Ich meine, Sie beweisen keine Position in Ihrem Konstruktor, daher ist es nicht möglich, den Speicherort festzulegen, wenn Sie Ihre Konstruktorparameter nicht ändern. Daher sollten Sie erwarten, dass es sich um die Standardwerte handelt. Sie sollten Parameter für den Standort hinzufügen. [Sie können Konstruktor in einem Konstruktor aufrufen] (https://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java), aber ich würde es nicht tun, es sei denn Es gibt einen guten Grund dazu. –