Class constructor default values
Suppose the following class:
Code Java:
public class Sample() {
private int xPos, yPos;
private int xSize = 10;
private int ySize = 10;
// - -
Sample(int xPos, int yPos, int xSize, int ySize) {
this.xPos = xPos;
this.yPos = yPos;
this.xSize = xSize;
this.ySize = ySize;
}
// - -
Sample(int xPos, yPos) {
this.xPos = xPos;
this.yPos = yPos;
//this.xSize = 10;
//this.ySize = 10;
}
// etc
}
... or should the second constructor be using the commented out lines instead? Or a different way?
Re: Class constructor default values
Either method will work (I tend to prefer initializing everything in a constructor rather than in the declaration). Also, there are some syntax errors with your code. You don't put parenthesis after the class declaration.
Here's how I go about handling multiple constructors:
Have all the initialization code inside the constructor which takes the most parameters.
All your other constructors should call this first constructor with the parameters it has and the other parameters to be set as default.
For example:
Code Java:
public class Sample{
private int xPos, yPos, xSize, ySize;
// this is the most complex constructor
Sample(int xPos, int yPos, int xSize, int ySize) {
this.xPos = xPos;
this.yPos = yPos;
this.xSize = xSize;
this.ySize = ySize;
}
Sample(int xPos, yPos) {
// simply call the other constructor with the params given to this constructor and the other parameters set to their default value
this(xPos, yPos, 10, 10);
}
}
Re: Class constructor default values
Quote:
... syntax errors ...
lol @ me
I guess I should actually read things when I press the preview button...
Thanks for the reply. :)
Re: Class constructor default values
np, that's what the edit button's for :D