Say we want to make a tree. Therefore, we create the object: Tree.
in Java code:
Tree blackTree = new Tree();
A tree has a length of 5 cm:
If you cut a three in half. The two halfs got a length, the moment that they were split. One way to deal with it is: delete the old object
create two new ones:
There are many ways to achieve this RESULT, one is correct:
make a method in which you can edit the height
package ConstructorExplanation;
public class Main {
void start () {
Tree upperHalf = new Tree();
Tree lowerHalf = new Tree();
upperHalf.addHeight(2.5);
lowerHalf.addHeight(2.5);
}
public static void main(String[] args) {
new Main().start();
}
} |
package ConstructorExplanation;
public class Tree {
double heightTree;
void addHeight (double inputHeight) {
heightTree = inputHeight;
}
} |
only make a variable height in the object class
package ConstructorExplanation;
public class Main {
void start () {
Tree upperHalf = new Tree();
Tree lowerHalf = new Tree();
}
public static void main(String[] args) {
new Main().start();
}
} |
package ConstructorExplanation;
public class Tree {
double heightTree = 2.5;
} |
- make a constructor, now you can directly give the tree a height 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();
}
} |
package ConstructorExplanation;
public class Tree {
double heightTree;
Tree (double inputHeight) {
heightTree = inputHeight;
}
} |
example summary
Point 3 is the best, in this case. Because at the moment you have cut the tree, the height of the two new objects is a fact, the moment you cut the tree.
- It saves lines of code.
- And height should be a variable as soon as possible
- if you cut a three in half. The two halfs have a height the moment that they were split
- Therefore, it should be a bit weird if you first create those objects without a height and after a while give them a height.