Java: Multiple Constructors
You can build multiple constructors, and it calls the correct constructor depending on how many arguments you specify.
Take a look at the following example:
class ClassOne{
private int energy;
private int speed;
private int endurance;
public ClassOne(){
this(0, 0, 0);
}
public ClassOne(int e){
this(e, 0, 0);
}
public ClassOne(int e, int s){
this(e, s, 0);
}
public ClassOne(int e, int s, int en){
Setattributes(e, s, en);
}
void Setattributes(int energy, int speed, int endurance){
this.energy = energy;
this.speed = speed;
this.endurance = endurance;
}
void PrintAttributes(){
System.out.println("Energy " + this.energy + "\nSpeed " + this.speed + "\nEndurance " + this.endurance + "\n");
}
};
public class Main
public static void main(String[] args) {
ClassOne Object = new ClassOne(12);
Object.PrintAttributes();
ClassOne Object2 = new ClassOne(12, 22);
Object2.PrintAttributes();
ClassOne Object3 = new ClassOne(12, 22, 63);
Object3.PrintAttributes();
}
}
The only bits that you wont understand in this our bits like this:
this(e, 0, 0);
In the case of the example where only one parameter is in the constructor, it takes that one, and then gives it another two, because it now has three it calls the constructor with the parameters and then does as appropriate.
This is the basis of multiple constructors.
Back to Java

