You can add multiple constructors in Java.
As in the example with the trees. You initialise the moment that you create the new object.
package ConstructorExplanation;
public class Tree {
double heightTree;
Tree(double inputHeight) {
heightTree = inputHeight;
}
}
Therefore, you add a value when you create the object
package ConstructorExplanation;
public class Main {
void start () {
Tree upperHalf = new Tree(2.5);
Tree lowerHalf = new Tree(2.5);
}
public static void main(String[] args) {
new Main().start();
}
}
Theory
I can add multiple extra constructors with other parameters
example
Besides height, I can also make a constructor with variable typeOfPlant.
package ConstructorExplanation;
public class Tree {
double heightTree;
String typeOfPlant;
Tree(double inputHeight) {
heightTree = inputHeight;
}
Tree(double inputHeight, String inputType) {
heightTree = inputHeight;
typeOfPlant = inputType;
}
}
How does java know which constructor I need when I create a new object?
Java checks the parameters you put in:
package ConstructorExplanation;
public class Main {
void start () {
Tree smallTree = new Tree(2.5);
Tree bigPalm = new Tree(5, "palm tree");
}
public static void main(String[] args) {
new Main().start();
}
}
Now Java created 2 objects:
THEREFORE,
Something like this will not work, because now Java doesn’t know which constructor you want to call: